gpt4 book ai didi

C - 多个左值错误

转载 作者:行者123 更新时间:2023-11-30 15:21:18 24 4
gpt4 key购买 nike

我想做一个简单的程序,对用户输入的整数求和,只要用户按顺序输入它们(奇数、偶数、奇数 (..)),只要总和小于 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() 不消耗尾随空白字符,因此您可能需要使用 getchar 从 stdin 缓冲区中手动提取它们()fgetc()

关于C - 多个左值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com