为什么结果是onetwothree40 50 0而不是onetwothreethis结束... 40 50 0? [英] Why the result is onetwothree40 50 0 and not onetwothreethis is the end...40 50 0 ?
问题描述
#include <stdio.h>
int main()
{
int i=10,j=20,k=0;
if(i=40)
printf("One");
if(j=50)
printf("Two");
if(k=60)
printf("Three");
if(k=0)
printf("This is the end...");
printf("%d %d %d\n",i,j,k);
}
我的尝试:
为什么结果是onetwothree40 50 0而不是onetwothreethis是结束... 40 50 0 ??
What I have tried:
Why the result is onetwothree40 50 0 and not onetwothreethis is the end...40 50 0 ??
推荐答案
那是因为=
是一个赋值运算符。
你需要使用==
进行比较。
尝试 -
That's because=
is an assignment operator.
You need to use==
for comparision.
Try-
int main()
{
int i=10,j=20,k=0;
if(i==40)
printf("One");
if(j==50)
printf("Two");
if(k==60)
printf("Three");
if(k==0)
printf("This is the end...");
printf("%d %d %d\n",i,j,k);
}
希望,它有帮助:)
Hope, it helps :)
正如 Suvendu Shekhar Giri ,您正在使用赋值运算符而不是相等的测试。现在在C
编程语言中,构造
As suggested by Suvendu Shekhar Giri, you are using the assignment operator instead of the test for equality. Now inC
programming language, the construct
i=40
是一个表达式,其评估值为 40
。所以写了
is an expression, whoose evaluation is 40
. So writing
if (i=40)
结束于
ends up in
if (40)
这是 中的
条件(任何数字,但 0
假定为 true
)
这就是你得到这种意外输出的原因。
That is a true
condition in the if
(any number but 0
is assumed to be true
)
That's the reason you're getting such unexpected output.
为什么结果是onetwothree40 50 0而不是onetwothreethis是结束... 40 50 0?
Why the result is onetwothree40 50 0 and not onetwothreethis is the end...40 50 0 ?
因为在C中,任何整数都是 true
但是值0是 false
。
小心,同时在中确定一个值,如果
条件合法,则通常是不需要的并且是新手的常见错误。
以下是语言作者对C和C ++参考书的链接。注意,C是C ++的祖先,所以知道C对C ++总是有用。
C编程语言 - 维基百科,免费的百科全书 [ ^ ]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2。 pdf [ ^ ]
http://www.ime.usp。 br / ~pf / Kernighan-Ritchie / C-Programming-Ebook.pdf [ ^ ]
C ++编程语言 [ ^ ]
Because in C, any integer is true
but the value 0 which is false
.
Be careful, while assinging a value in a if
condition is legal, it is often unwanted and a common error of newbies.
Here is links to references books on C and C++ by the authors of the languages. Note than C is the ancestor of C++, so knowing C is always useful with C++.
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]
C++ Programing Language[^]
这篇关于为什么结果是onetwothree40 50 0而不是onetwothreethis结束... 40 50 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!