我必须在没有更新( ++或- process)的情况下创建一个while循环,如下所示。但是,在将来自用户(Y)的响应存储在ans变量中之后,循环不执行。
#include <stdio.h>
void main ()
{
float volt, ohms, power;
char ans;
printf ("Enter 'Y' to continue : ");
scanf ("%c", &ans);
while (ans=="Y" || ans=="y");
{
printf ("\nEnter the voltage value (Volt) : ");
scanf ("%f", &volt);
printf ("Enter the resistance value (Ohms) : ");
scanf ("%f", &ohms);
power = (volt*volt)/ohms ;
printf ("\nVoltage : %.2f \nResistance : %.2f \nPower : %.2f", volt, ohms, power);
fflush(stdin);
printf ("\n\nEnter 'Y' to continue : ");
scanf ("%c", &ans);
}
}
发布于 2020-12-24 02:40:34
我刚抓到它。这是语法错误。嗯,有几个。
你写的
while (ans=="Y" || ans=="y");
看到最后的;
了吗?这意味着while循环执行一个空语句,而不是下一行中的块。
如果您已经构建了完整的警告,并且使用了现代的编译器,那么您将得到一个关于空循环的警告。
还请注意,您正在尝试将单个字符char ans
与字符串文本"Y"
(即数组,而不是字符)进行比较。你需要写:
while (ans == 'Y' || ans == 'y')
当我使用完整的警告标志gcc -W -Wall -pedantic
时,我的GCC版本9.3.0就是这样做的
c-scanf-test.c: In function ‘main’:
c-scanf-test.c:10:14: warning: comparison between pointer and integer
10 | while (ans == "Y" || ans == "y");
| ^~
c-scanf-test.c:10:14: warning: comparison with string literal results in unspecified behavior [-Waddress]
c-scanf-test.c:10:28: warning: comparison between pointer and integer
10 | while (ans == "Y" || ans == "y");
| ^~
c-scanf-test.c:10:28: warning: comparison with string literal results in unspecified behavior [-Waddress]
c-scanf-test.c:10:3: warning: this ‘while’ clause does not guard... [-Wmisleading-indentation]
10 | while (ans == "Y" || ans == "y");
| ^~~~~
c-scanf-test.c:11:3: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘while’
11 | {
| ^
c-scanf-test.c:8:3: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
8 | scanf("%c", &ans);
| ^~~~~~~~~~~~~~~~~
c-scanf-test.c:13:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
13 | scanf("%f", &volt);
| ^~~~~~~~~~~~~~~~~~
c-scanf-test.c:15:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
15 | scanf("%f", &ohms);
| ^~~~~~~~~~~~~~~~~~
c-scanf-test.c:24:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result [-Wunused-result]
24 | scanf("%c", &ans);
| ^~~~~~~~~~~~~~~~~
您可以看到,您还有许多其他错误要修复。
https://stackoverflow.com/questions/65433257
复制相似问题