C - 多个左值错误
C - multiple lvalue errors
我想做一个简单的程序,对用户输入的整数求和,只要用户按顺序输入它们(奇数,偶数,奇数(..))只要总和小于100. 这是我的代码。
#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 语句会给我一个左值错误?也抱歉弱智代码,才刚刚开始。
c中的比较运算符是==
不是=
,=
是赋值运算符,所以
while (1 = 1)
表示把1
赋值给1
当然不可能,改成
while (1 == 1)
甚至
while (1)
但是 while 循环的更好条件是
while ((scanf("%d", &b) == 1) && (b % 2 != 0))
尽管您应该意识到循环将在无效输入时结束这一事实,但您可以防止未定义的行为。
而且,你这里有错误
scanf("%d , &a");
您将 &a
作为格式字符串的一部分传递,这是错误的,应该是
scanf("%d", &a);
请注意 scanf()
不会消耗尾随的白色 space 字符,因此您可能需要使用 getchar()
或从 stdin
缓冲区中手动提取它们fgetc()
.
我想做一个简单的程序,对用户输入的整数求和,只要用户按顺序输入它们(奇数,偶数,奇数(..))只要总和小于100. 这是我的代码。
#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 语句会给我一个左值错误?也抱歉弱智代码,才刚刚开始。
c中的比较运算符是==
不是=
,=
是赋值运算符,所以
while (1 = 1)
表示把1
赋值给1
当然不可能,改成
while (1 == 1)
甚至
while (1)
但是 while 循环的更好条件是
while ((scanf("%d", &b) == 1) && (b % 2 != 0))
尽管您应该意识到循环将在无效输入时结束这一事实,但您可以防止未定义的行为。
而且,你这里有错误
scanf("%d , &a");
您将 &a
作为格式字符串的一部分传递,这是错误的,应该是
scanf("%d", &a);
请注意 scanf()
不会消耗尾随的白色 space 字符,因此您可能需要使用 getchar()
或从 stdin
缓冲区中手动提取它们fgetc()
.