如何解决在我的条件变量中存储 char Y来自用户的循环输入后,我的 while 循环仍然没有执行?
我必须在没有更新的情况下进行 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,power);
fflush(stdin);
printf ("\n\nEnter 'Y' to continue : ");
scanf ("%c",&ans);
}
}
解决方法
我刚刚抓住了它。这是一个语法错误。嗯,一对。
你写的
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);
| ^~~~~~~~~~~~~~~~~
您可以看到您有许多其他错误需要修复。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。