gpt4 book ai didi

c - 为什么当变量不相等时语句为真,而当变量相等时语句为假?

转载 作者:行者123 更新时间:2023-11-30 20:52:46 25 4
gpt4 key购买 nike

我昨天刚开始学习 C,遇到了一个问题,但我不明白为什么会发生。

代码是这样的

#include<stdio.h>
int a=0;
void main() {
if (a=13) {
printf("Number Is Equal\n");
}
else {
printf("Not Equal\n");
}
}

它应该显示不等于,但它仍然显示数字相等,我也尝试了其他数字来代替 int a;如果我分配 int a=13 的值,然后如果我运行语句 if(a=13) 那么它是真的,但是如果我在两个地方都对 0 执行相同的操作,那么它显示不相等。

最佳答案

您使用赋值运算符 =13 赋给 a。使用 == 进行比较。

示例:

int a=0;
void main()
{
// Here, a is being checked to see if it is equal to the int 13.
// a=13 would be assigning 13 to a, and then checking to see if
// a is "truthy", or, not 0, which is why it was true for you every time.
if (a == 13) {
printf("Number Is Equal\n");
}else{
printf("Not Equal\n");
}
}

NOTE: The C Standard specifies that main() will return type int, (e.g. int main(){return 0;}) when in a hosted environment. You can deviate from this when you're in a freestanding environment, at which point this becomes implementation defined. It is not likely that you are using a freestanding environment. The odds are that you are in a hosted environment where your use of type void for main would violate the C Standard.

关于c - 为什么当变量不相等时语句为真,而当变量相等时语句为假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57625891/

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