繁体   English   中英

在我的条件变量中存储 char Y(来自用户的循环输入)后,我的 while 循环仍未执行?

[英]After storing the char Y (input from user for looping) in my condition variable, my while loop still not executing?

我必须在没有更新(++ 或 -- 过程)的情况下进行 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);
    }
}

我刚抓住它。 这是一个语法错误。 嗯,一对。

你写了

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);
      |     ^~~~~~~~~~~~~~~~~

您可以看到您还有许多其他错误需要修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM