2010-01-02 97 views
2

错误消息:C++错误C2040?

这是什么意思?

我该如何解决?

错误C2040: '==': '诠释' 的不同之处,从 '为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)); 
} 
+0

我一看到问题就看到了问题,但这是一个非常无益的编译器错误消息。不难理解为什么人们会对C及其同类感到沮丧。 – 2010-01-02 08:58:27

回答

10

你需要单引号char文字。您正确地这样做的第一个而不是第二:

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

这应该是:

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

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

+0

谢谢,我需要开始关注C++中的所有小细节。 – user242229 2010-01-02 10:23:12

+0

你可以试试这个:'while(toupper(ans)=='Y');' – 2010-01-02 19:29:46

1

你有双引号,而不是在这条线单一的:

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

资本Y被包含在双引号中,它创建了一个const char [2](Y后跟空)。你可能包换:

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

我不知道这是否有用,但它可能会像下面:

,而((ANS == 'Y')||(ANS == 'Y') );

+1

分号是必需的,因为这是do-while语句的结尾(而不是while语句)。 – 2010-01-02 09:09:57

+0

好的抱歉,我还没有看到它是一个做while语句。好 – Pranjali 2010-01-02 09:33:46