c/c++语言开发共享C简易程序不工作 – “如果”

我试着编写一个简单的程序,比较3个数字并打印出最大的数字,但它会继续打印所有3个数字而且我不明白为什么。 那是我的代码:

#include  int main() { int x = 10; int y = 8; int z = 3; if((x > y) && (x > z)); { printf("%d",x); } if((y > x) && (y > z)); { printf("%d",y); } if((z > x) && (z > y)); { printf("%d",z); } return 0; } 

谢谢您的帮助!

    删除每个if语句末尾的分号。 这导致if语句运行null语句(;)然后运行块语句{printf(…); }

     #include  int main() { int x = 10; int y = 8; int z = 3; if((x > y) && (x > z)) { printf("%d",x); } if((y > x) && (y > z)) { printf("%d",y); } if((z > x) && (z > y)) { printf("%d",z); } return 0; } 

    你应该使用else,你应该在if语句之后删除分号,ifs之后的半冒号意味着if的主体是空的而其他东西是正常的代码块

     #include  int main() { int x = 10; int y = 8; int z = 3; if((x > y) && (x > z)) { printf("%d",x); } else { // Will not make difference in this particular case as your conditions cannot overlap if((y > x) && (y > z)) { printf("%d",y); } else { // Will not make difference in this particular case as your conditions cannot overlap if((z > x) && (z > y)) { printf("%d",z); } } } return 0; } 

    if条件之后你有一个分号:

     if((x > y) && (x > z)); 

    当条件为真时,分号取代要执行的块或语句。 就像你写的那样:

     if((x > y) && (x > z)) { ; } { printf("%d",x); } 

    您可以希望看到它将如何无条件地执行print语句。

    您的问题的答案纯粹基于在C语言中使用分号和if语句的语法的知识。

    有关更多信息,请阅读分号并清楚了解if 语法 。

    如果您使用额外的变量来获得最大值,则逻辑会更简单

     #include  int main() { int x,y,z, max; scanf ("%d", &x); max = x; scanf ("%d", &y); if (y > max) max = y; scanf ("%d", &z); if (z > max) max = z; printf ("max = %d", max); return 0; } 

      以上就是c/c++开发分享C简易程序不工作 – “如果”相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522873.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐