2015-04-12 27 views
0

只要用戶在序列中輸入它們(奇數,偶數,奇數(..)),我想製作一個簡單的程序,用於求和用戶輸入的整數,只要求和低於100.這是我的代碼。C - 多個左值錯誤

#include <stdio.h> 

int check_odd(int x) 
{ 
    int i = x - 1; 
    int o; 
    for (i = x - 1; i > 1; i--) 
    { 
     if (x % i = 0) 
     { 
      o = 1; 
      break; 
     } 
    } 

    if (o != 1) 
    { 
     o = 0; 
    } 

    return o; 
} 

int check_even(int x) 
{ 
    int i; 
    i = x/2; 

    if (i * 2 = x) 
    { 
     x = 1; 
    } 
    else x = 0; 

    return x; 
} 

int main() 
{ 
    int a; 
    int b; 
    int s = 0; 

    while (s < 100) 
    { 
     while (1 = 1) 
     { 
      printf("Enter an odd number\n"); 
      scanf("%d , &a"); 
      b = check_odd(a); 

      if (b = 1) 
      { 
       s = s + a; 
       printf("Current sum equals %d , &s\n"); 
       break; 
      } 

      printf("Entered number is incorrect. Try again.\n"); 
     } 

     while (1 = 1) 
     { 
      printf("Enter an even number\n"); 
      scanf("%d , &a"); 
      b = check_even(a); 

      if (b = 1) 
      { 
       s = s + a; 
       printf("Current sum equals %d , &s\n"); 
       break; 
      } 
      printf("Entered number is incorrect. Try again.\n"); 
     } 
    } 
printf("Sum equals $d , &s\n"); 
} 

現在,我得到線

if (x % i = 0) 

if (i * 2 = x) 

while (1 = 1) 

我做了什麼錯,爲什麼在地球上1 = 1的語句給我一個左值誤差左值錯誤?對於延遲代碼也很抱歉,剛開始。

回答

1

C中的比較運算符是====被賦值運算符,所以

while (1 = 1) 

手段分配11這當然是,不可能的,它更改爲

while (1 == 1) 

或甚至

while (1) 

但while循環更好的條件會是這樣的

while ((scanf("%d", &b) == 1) && (b % 2 != 0)) 

雖然你應該知道的事實,即循環將結束對輸入無效,但你會防止未定義行爲。

而且,你這裏有一個錯誤

scanf("%d , &a"); 

你逝去的&a作爲格式字符串,這是不對的一部分,它應該是

scanf("%d", &a); 

請注意scanf()不消耗尾隨空白字符,因此您可能需要使用getchar()fgetc()stdin緩衝區中手動提取它們。