2015-06-27 632 views
0

我正在做這個簡單的代碼,如果我把兩個數字,它顯示的解決方案。這是代碼:錯誤未在此範圍內聲明

#include <stdio.h> 

int main() 
{ 
    printf("Enter two numbers:") 
    ;scanf("&d &d", a, b) 
    ;printf("=======================\n"); /* */ 
    /* */ 
    printf("The sum of %d and %d is %d.\n\n", 3, 4, 3 + 4) 
    /* */ 
    ;printf("The difference of %d and %d is %d. \n\n", 3, 4, 3-4) 
    /* */ 
    ;printf("The product of %d and %d is %d. \n\n", 3, 4, 3*4) 
    /* sum of squares would be a*a + b*b */ 
    ;printf("The sum of the squares of %d and %d is %d. \n\n", 3, 4, 3*3 + 4*4) 
    ;printf("**end**"); /* :-) */ 
    ;return (0); 
} 

,我不斷收到一個錯誤,指出:

[Error] 'a' was not declared in this scope 
and 
[Error] 'b' was not declared in this scope 

這有什麼錯呢?

+0

您需要聲明它們,正如它所說的那樣。像「int a,b;」 –

+0

有趣的風格:_(。 – this

+0

你需要聲明變量a和b,然後再嘗試在其中存儲任何內容 – tylerism

回答

0

您需要在嘗試存儲任何內容之前聲明變量。

int a,b; 

該行必須是主函數的第一行。

編輯:確保你的代碼看起來像這樣?

int main() 
{ 
    int a,b; 
    printf("Enter two numbers:") 
    ;scanf("&d &d", a, b) 
    ;printf("=======================\n"); /* */ 
    /* */ 
    printf("The sum of %d and %d is %d.\n\n", 3, 4, 3 + 4) 
    /* */ 
    ;printf("The difference of %d and %d is %d. \n\n", 3, 4, 3-4) 
    /* */ 
    ;printf("The product of %d and %d is %d. \n\n", 3, 4, 3*4) 
    /* sum of squares would be a*a + b*b */ 
    ;printf("The sum of the squares of %d and %d is %d. \n\n", 3, 4, 3*3 + 4*4) 
    ;printf("**end**"); /* :-) */ 
    ;return (0); 
} 
+0

我到底在哪裏呢? p.sim新手 – Naxs

+0

@納克斯之前,你使用的變量。所以在調用scanf()之前基本上就是這樣。有時最好在函數的開頭聲明所有變量,使函數中使用的變量更清晰一些。 –

+0

好,所以我做了你告訴我的,但「輸入兩個數字」從我的輸出中丟失 – Naxs

1

首先聲明如果兩個變量缺失。 首先聲明它們,你的情況INT將是最好的,所以:

int a, b; 

,那麼你還需要指針傳遞給scanf()的函數,因此它可以在變量值寫入,就像這樣:

scanf("%d %d", &a, &b); 

這也是一個很好的做法,檢查值是否已被讀取或沒有。 scanf()返回它從輸入中成功解析的值的數量,所以在你的情況下,如果成功,它應該返回2,測試它。

而且它不是一個壞主意,初始化變量一樣,所以也許那樣做,而不是:

int a = 0, b = 0; 

還你似乎沒有被使用在你的程序的其餘部分的變數,你可能想要做些什麼。

0

1.使用前必須聲明變量。 您在下面的行中使用a和b。但你以前沒有宣佈過。所以它肯定會給你錯誤。

scanf("&d &d", a, b); 

2.It的也必須使用「&」 A和B,而從用戶獲得價值。它不會給你錯誤,但可以給你不正確的結果,你不想要的。

scanf("&d &d", &a, &b); 

3.壓入也不好。你需要使用';'在陳述結束時,而不是在陳述下一個陳述或任何其他編碼行之前。它不會給你錯誤,但它很容易理解代碼和易讀性。

printf("Enter two numbers:") 
;scanf("&d &d", a, b) 
+0

如果格式字符串不包含任何格式說明符(例如'%d'),那麼它的參數是多餘的 –