【问题标题】:Using Char in an if statement C++在 if 语句 C++ 中使用 Char
【发布时间】:2013-07-12 15:58:58
【问题描述】:

伙计们,我正在尝试使用带有 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;
}

【问题讨论】:

  • 未知标识符printf。你忘了#include &lt;stdio.h&gt;(或&lt;cstdio&gt;
  • @Borgleader:为什么这不是 C++?有没有 C++ 语言之外的语句?
  • @ThomasMatthews printf、scanf、char 数组。这是 C 代码,因此应标记为 C。
  • @Borgleader:我可以在 C++ 下编译它。 C++ 标签是否意味着问题必须使用一些 C 语言中没有的 C++ 语言元素?
  • 想知道为什么他得到了iostream...

标签: c++ if-statement char


【解决方案1】:

您处理 char 数组的方式存在一些问题。

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

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

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

【讨论】:

  • 另外,如果response 是一个字符数组,scanf ("%s", &amp;response) 会调用 UB。
  • 感谢 Tribse 的建议。我现在就开始学习字符串的工作原理。
【解决方案2】:

没有检查所有的代码,但是你使用了一个

operator ==

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

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2014-01-02
    • 1970-01-01
    • 2018-02-09
    • 2013-10-07
    相关资源
    最近更新 更多