【问题标题】:C++ Error C2040?C++ 错误 C2040?
【发布时间】:2010-01-02 08:50:59
【问题描述】:

错误信息:

这是什么意思?

我该如何解决?

错误 C2040:“==”:“int”与“const char [2]”的间接级别不同

代码:

#include <iostream>
#include <cmath>
using namespace std;

int round(double number);
//Assumes number >=0.
//Returns number rounded to the nearest integer.

int main()
{
    double doubleValue;
    char ans;

    do
    {
        cout << "Enter a double value: ";
        cin >> doubleValue;
        cout << "Rounded that number is " <<round(doubleValue)<< endl;
        cout << "Again? (y/n): ";
        cin >> ans;

    }
    //Here is the line generating the problem, while(...);

    while (ans == 'y' || ans == "Y");

    cout << "End of testing.\n";

    return 0;
}

//Uses cmath
int round(double number)
{
    return static_cast<int>(floor(number + 0.5));
}

【问题讨论】:

  • 我在您指出该行后就看到了问题,但这是一个非常无用的编译器错误消息。不难看出为什么人们对 C 及其类似语言感到沮丧。

标签: c++


【解决方案1】:

您需要单引号 char 文字。您对第一个正确执行此操作,但对第二个未正确执行:

while (ans == 'y' || ans == "Y");

这应该是:

while (ans == 'y' || ans == 'Y');

双引号用于字符串 (const char[]) 文字。

【讨论】:

  • 谢谢,我需要开始更加关注 C++ 中的所有小细节。
  • 你可以试试这个:while (toupper(ans) == 'Y');
【解决方案2】:

您在这一行使用双引号而不是单引号:

while (ans == 'y' || ans == "Y");

【讨论】:

    【解决方案3】:

    大写的 Y 包含在双引号中,这将创建一个 const char [2](Y 后跟 null)。你可能会提醒:

    while (ans == 'y' || ans == 'Y');
    

    【讨论】:

      【解决方案4】:

      我不知道这是否有用,但可能如下所示:

      while ((ans == 'y') || (ans == 'Y'));

      【讨论】:

      • 分号是必需的,因为这是 do-while 语句的结尾(而不是 while 语句)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 2017-08-01
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多