在if语句C++中使用Char

Using Char in an if statement C++

本文关键字:Char C++ if 语句      更新时间:2023-10-16

各位,我试图使用带有char变量的"if"语句,但它似乎没有注意到何时满足"yes"条件。我不知道在没有数组的情况下是否有办法做到这一点。下面是我的代码。非常感谢您的帮助。

// Running times calculator
# include <iostream>
# include <math.h>
using namespace std;
int main ()
{
    float cTime;
    float gTime;
    float cDist;
    float gDist;
    float min;
    float sec;
    float cMin;
    float cSec;
    float p1000;
    char response[1];
    int blank;
    printf ("Welcome to the running times calculator.nnEnter your completed race distance in metres: n");
    scanf ("%f", &cDist);
    printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit entern");
    scanf ("%f" "%f", &cMin, &cSec);
    cTime = cSec+(60*cMin);
    p1000 = pow(1000/cDist,1.1)*cTime;
    printf ("Would you like to enter another race time to improve prediction accuracy? n");
    scanf ("%s", &response);
    if(response == "yes")
    {
       printf ("Enter your completed race distance in metres: n");
       scanf ("%f", &cDist);          
       printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit entern");
       scanf ("%f" "%f", &cMin, &cSec);
       cTime = cSec+(60*cMin);
      p1000 = ((pow(1000/cDist,1.1)*cTime)+p1000)/2;
    }
    printf ("What is your goal race distance in metres? n");
    scanf ("%f", &gDist);
    gTime = pow(gDist/1000, 1.1)*p1000;
    min = gTime/60;
    sec = remainder(gTime,60);
    if (sec < 0)
    {
    sec = sec + 60;
    min = min - 1;    
    }
    printf ("Your predicted time for a race of %.0f metres is %.0f minutes and %.0f seconds", gDist, min, sec);
    scanf("%f", &blank);
    return 0;
}

您在处理char数组时遇到了一些问题。

char response[1];您在这里创建了一个由一个字符组成的char数组,但随后您将其视为以下行中的字符串:

scanf ("%s", &response);if(response == "yes")

还要注意,您不能简单地将char数组和字符串文字与==进行比较,您所要做的只是比较地址。您要么必须使用strcmp(),要么最好使用std::string。

没有检查所有代码,但您使用了

operator ==

不适用于char[],它用于字符串请改用strcmp。