在if语句C ++中使用Char

时间:2013-07-14 20:02:50

标签: c++ if-statement char

伙计们,我正在尝试使用带有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.\n\nEnter your completed race distance in metres: \n");
    scanf ("%f", &cDist);
    printf("Enter your completed race time. Type minutes, hit enter. Type seconds, hit enter\n");
    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 enter\n");
       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;
}

2 个答案:

答案 0 :(得分:3)

你对char数组的处理方式有些问题。

char response[1];你创建一个由一个字符组成的字符数组,但是在这些行中你将它视为一个字符串:

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

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

答案 1 :(得分:0)

未检查所有代码,但您使用

operator ==

不能用于char [],它是用于字符串的 改用strcmp。