这个程序的输出是什么? [英] what will be the output of this programme?

查看:86
本文介绍了这个程序的输出是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
    void main()
    {
        int x = 0;
        if (x = 0)
            printf("Its zero\n");
        else
            printf("Its not zero\n");
    }

推荐答案

程序不起作用,因为您正在使用赋值运算符,您需要使用相等检查运算符。正如理查德在上面所说的,这就是为什么结果是相反的而不是你所期望的。



如果(x = 0)将表达式解析为零,会发生什么。在C / C ++中,整数直接解析为布尔值,所有非零都是真值,零是假。由于此解析为零,表达式为false,控制权转移到 else 块。



重新以这种方式写,



The program doesn't work because you are using assignment operator where you need to use the equality check operator. That is why the results are opposite and not what you had expected, as Richard said above.

What happens is that if(x = 0) would resolve the expression to zero. In C/C++, integers are directly resolved to boolean, everything non-zero is a true value and zero is the false. Since this resolves to zero, the expression is false and control is transferred to the else block.

Re-write it in this manner,

#include <stdio.h>
void main()
{
    int x = 0;
    if (!x) { // If zero, then true, otherwise false. 
        printf("Its zero\n");
    }
    else {
        printf("Its not zero\n");
    }
}





还记得添加 {} 围绕这些陈述,这不是一个好习惯,因为你可能会混淆自己或错误地添加分号,编译器不会抱怨,但逻辑是错误的。



有关C运营商的更多信息,请参阅本教程: http ://www.tutorialspoint.com/cprogramming/c_operators.htm [ ^ ]



Also remember to add the { } around the statements, it is not a good practice as you may confuse yourself or add a semicolon by mistake, compiler will not complain but the logic would be wrong.

For more on C operators please refer to this tutorial: http://www.tutorialspoint.com/cprogramming/c_operators.htm[^]


由于您没有指定可执行文件,因此编译程序时会出错。

为了您的良好工作在你的问题中编程声明的变量(x)可能不会被初始化。因为初始化变量有一个定义的值。为了在你的问题中执行if else语句,输入应由你和它给出可以通过输入函数(scanf)继承。为了保持稳定性,使用头文件conio.h和getch();功能。



请使用以下代码供您参考:



Since you didn't specify the executable there would be an error while compiling your program.
For fine working of your program the declared variable(x) in your question may not be initialized.Because initialized variables have a defined value.In order to execute the if else statement in your question the input should be given by you and it can be succeeded by an input function(scanf). In-order to keep the stability use the header file conio.h and getch(); function.

kindly use the below code for your reference:

#include<stdio.h>
#include<conio.h>
void main()
{
 int x;
 printf("please enter your number");
 scanf("%d",&x);
 if(x==0)
 printf("It is zero");
 else
 printf("It is non zero");
getch();
}


这篇关于这个程序的输出是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆