2010-01-02 93 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