在我的条件变量中存储 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 版本 9.3.0 在我使用完整警告标志时执行此操作 gcc -W -Wall -pedantic:

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

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