2009-02-16 10 views
1

爲了說明的目的,我需要程序打印輸入的數字和a和b,而不是實際的字母a和b。
好這裏的每亞勒的建議,修訂後的計劃:? (在C)*更新*

int main (int argc, char *argv[]) 
{ 
    int a; /*first number input*/ 
    int b; /*second number input*/ 

    a = atoi(argv[1]); /*assign to a*/ 
    b = atoi(argv[2]); /*assign to b*/ 

    if (a < b) 
     printf("%s\n", a < b); /* a is less than b*/ 
     else { 
     printf("%s\n", a >= b); /* a is greater than or equal to b*/ 
     } 

    if (a == b) 
     printf("%s\n", a == b); /* a is equal to b*/ 
     else { 
     printf("%s\n", a != b); /* a is not equal to b*/ 
     } 

    return 0; 
} /* end function main*/ 

笑,現在當我運行程序我得到告訴

 
8 [main] a 2336 _cygtls::handle_exceptions: Error while dumping state 
Segmentation fault 

到底什麼意思呢? (如果你現在還沒有注意到我對這個東西很沒有希望)。

+0

如果你打算這樣做,你必須在你的語句中包含引號。 「a kgrad 2009-02-16 04:12:28

+0

你忘了給程序提供兩個參數 - 因此seg故障和核心轉儲。 – 2009-02-16 05:11:35

回答

2

根據您的修改,我認爲你正在尋找這樣的:

#include <stdio.h> 

int main (int argc, char *argv[]) { 
    int a; /*first number input*/ 
    int b; /*second number input*/ 

    a = atoi(argv[1]); /*assign to a*/ 
    b = atoi(argv[2]); /*assign to b*/ 

    if (a < b) 
     printf("%d < %d\n", a, b); /* a is less than b*/ 
    else 
     printf("%d >= %d\n", a, b); /* a is greater than or equal to b*/ 

    if (a == b) 
     printf("%d == %d\n", a, b); /* a is equal to b*/ 
    else 
     printf("%d != %d\n", a, b); /* a is not equal to b*/ 

    return 0; 
} 

此代碼:

[email protected]:~$ ./foo 1 2 
1 < 2 
1 != 2 
7

您要求printf()輸出布爾表達式的值(它們分別爲true和false時總是解析爲1或0)。

你可能想你的代碼看起來更像:

if (a < b) 
    printf("%s\n", "a < b"); /* a is less than b*/ 
else { 
    printf("%s\n", "a >= b"); /* a is greater than or equal to b*/ 
} 

顯示結果爲字符串。

+0

在關於布爾表達式的標記上。但請注意,printf()語句可分別由puts(「a = b」)替換。 – DevSolar 2009-02-16 03:58:59

6

這條線:

if (a = b) 

應該不會是

if (a == b) 

同樣在這裏:

printf("%d\n", a = b); /* a is equal to b*/ 

應該

printf("%d\n", a == b); /* a is equal to b*/ 
0

你的問題是,你試圖用邏輯表達式來代替整數。所有上述(a> b)...評估爲真或假(除了將b的值賦予a的a = b)。什麼,你應該做的,如果你想返回較大的值,如下:


    printf("%d\n", a > b ? a : b) 

這是說,如果大於b,打印,否則灣

編輯:我認爲你實際上想要的是打印出「a> b」等字樣。在這種情況下,把它們放在printf中。將%d放置在printf中時,它將指定的整數值代入字符串中的該點。

我相信你想要的以下內容:


    if(a > b) 
     printf("a > b\n"); 
    else 
     printf("b >= a\n"); 

是正確的嗎?

1
printf("%s\n", a == b); 

「%s」打印字符串。 a == b不是一個字符串,它是一個布爾表達式,導致1(真)或0(假)。

因此,您的printf()嘗試打印字符,直到它找到一個空字節,從布爾表達式... desaster的位置開始。

0

我假設你想是這樣的......

輸入:

1 = 5,B = 7

輸出:

5 = 7

如果是這樣,你需要打印的整數a和b! ,以及兩者之間的字符串以顯示關係。

if(a < b) { 
    printf("%d < %d\n", a, b); 
} 
else { 
    printf("%d >= %d\n", a, b); 
} 

// follow similar pattern for the next if/else block..