C语言 do while 和 if... else if... else的嵌套出错,急 C语言中while和if的嵌套

\u5173\u4e8e\u5728C\u8bed\u8a00\u4e2dWHILE\u4e0eIF\u3002\u3002\u3002ELSE\u7684\u5d4c\u5957\u95ee\u9898

\u7b49\u540c\u4e8e\u52a0\u4e0a\u62ec\u53f7
while\uff08\u6761\u4ef61\uff09
{
if\uff08\u6761\u4ef62\uff09
{
\u8868\u8fbe\u5f0f1\uff1b
}
else
{
\u8868\u8fbe\u5f0f2\uff1b
}
}

\u5b9e\u9645\u4e0a\u65f6\u8fd9\u6837\u7684\uff0c\u6761\u4ef61\u4e3a\u5047\u4ec0\u4e48\u90fd\u4e0d\u6267\u884c\uff0c\u6761\u4ef62\u4e3a\u5047\u6267\u884celse

\u76f8\u5f53\u4e8e
while\uff08\u8868\u8fbe\u5f0f1\uff09
{
if\uff08\u8868\u8fbe\u5f0f2\uff09
{
\u8868\u8fbe\u5f0f3\uff1b
}
else
{
\u8868\u8fbe\u5f0f4\uff1b
}
}
\u9996\u5148\u8fdb\u884c \u8868\u8fbe\u5f0f1 \u5224\u65ad\uff0ctrue\uff0c\u8df3\u5230if\u8bed\u53e5\uff0c\u5426\u5219\u9000\u51fa\u3002

\u4e0a\u9762while\u4e3atrue\uff0c
\u8fdb\u884c\u8868\u8fbe\u5f0f2\u5224\u65ad\uff0c
1.\u4e3atrue \u8fd0\u884c\u8868\u8fbe\u5f0f3\uff0c\u4e4b\u540e\u5728\u8df3\u5230while\u90a3 \u518d \u5224\u65ad
2.\u4e3afalse\u8fd0\u884c\u8868\u8fbe\u5f0f4\uff0c\u4e4b\u540e\u5728\u8df3\u5230while\u90a3\u518d\u5224\u65ad

#include<stdio.h>
#include<math.h>
void  main()  // 这里最好加上void 表示函数无返回值

  float n,x,y;
  int o,p;
  o=0;p=0;
  printf("Enter 7777 to STOP");
  do
  { printf("Enter a number:");
    scanf("%f
",&n);
    if(n=7777)   //  判断语句如果不写“{}”的话,默认只包含下面的第一行,所以这里没错,你只想执行这一行
 printf("Number of items done=%d Negative ite ms=%d",o,p);
else if(n>=0)    // 但是这里,你是想在n>=0的条件下执行下面的代码就需要加“{}”
{                // 而且if else  之间是不能加其他的代码的,所以需要加上“{}”
 x=n*n;
 printf("Square=%.5f
",x);
 y=sqrt(n);
 printf("root=%.5f
",y);
 o=o+1;
 }
else
{
 printf("Number if negative
");
 x=n*n;
 printf("square=%.5f
",x);
 p=p+1;
 }
   }while (n=7777);
   printf("Number of items done=%d Negative items=%d",o,p);
}     

谢谢


#include<stdio.h>
#include<math.h>
void main()

float n,x,y;
int o,p;
o=0;p=0;
printf("Enter 7777 to STOP
");
do

printf("Enter a number:");
scanf("%f",&n); //去掉回车
if(n==7777) //==才是比较
printf("Number of items done=%d Negative items=%d
",o+p,p);//o是非负数个数,p是负数个数
else if(n>=0)
{ //多条语句要用括号,else同
x=n*n;
printf("Square=%.5f
",x);
y=sqrt(n);
printf("root=%.5f
",y);
o=o+1;
}
else
{
printf("Number if negative
");
x=n*n;
printf("square=%.5f
",x);
p=p+1;
}
}while ( n!=7777 ); //条件应该是不等于
//printf("Number of items done=%d Negative items=%d",o,p); 本句多余
}


当if 或else 下有多条指令时应该用{}括起来。
if(){}
else if(){}
else{}

if 和 else之后有多个语句的时候,加大括号。

扩展阅读:do while用法举例 ... do while循环由do开始 ... do while至少循环一次 ... c语言的for循环例子 ... c中do while 语句 ... c语言中while 1 什么意思 ... c语言中do while循环 ... c语言do while循环排大小 ... while 1 为什么只循环一次 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网