2017-07-04 30 views
0

即時嘗試學習c + +,並不能找出這個錯誤的原因,它似乎匹配我的其他cout行不是'牛逼得到任何錯誤C++二進制>>找不到操作符,它需要一個右操作數類型的常量字符錯誤

#include "stdafx.h" 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int number = 42; 
    int guess; 
    bool notguessed = true; 
    while (notguessed); 

    cout << "Guess my number"; 
    cin >> "Guess"; 
    if (guess == number) 
    { 
     cout << "You got it" << endl; 
     notguessed = false; 
    } 
    if (guess < number) 
    { 
     cout << "To low try again" << endl; 
    } 
    if (guess > number) 
    { 
     cout << "To high try again" << endl; 
    } 


    return 0; 
} 
+0

'而(notguessed);'將阻塞下面一切... – WhatsUp

+0

要更明確的是,不要在'while'語句之後放置';'。 –

回答

0

你的程序有兩種錯誤 - 編譯錯誤和邏輯錯誤。

編譯錯誤 -考慮以下代碼段 -
cin >> "Guess"; 在這裏,你想給一個值恆定。你究竟想要做的是 - cin>>guess

邏輯錯誤 -當你做出上述改變你的代碼將編譯好的,但因爲你希望它是行不通的,這是因爲以下行 -
while (notguessed);
上面的while循環將無限運行,因爲notguessedtrue,並且沒有在循環中修改其值。
改變,要 -

while (notguessed){ 

    cout << "Guess my number"; 
    cin >> guess; 
    if (guess == number) 
    { 
     cout << "You got it" << endl; 
     notguessed = false; 
    } 
    else if (guess < number) 
    { 
     cout << "Too low try again" << endl; 
    } 
    else 
    { 
     cout << "Too high try again" << endl; 
    } 
} 

注 -我轉換了您簡單if語句if else if,這是爲了避免其他if S的不必要的檢查,當一個if已經評價true

有一種替代方法於上述其中通過使用break關鍵字使用變量notguessed,不需要 -

while (true){ 

    cout << "Guess my number"; 
    cin >> guess; 
    if (guess == number) 
    { 
     cout << "You got it" << endl; 
     break; 
    } 
    else if (guess < number) 
    { 
     cout << "Too low try again" << endl; 
    } 
    else 
    { 
     cout << "Too high try again" << endl; 
    } 
} 
1

試試這個代碼: -

# your code goes here 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int number = 42; 
    int guess; 
    bool notguessed = true; 
    cout << "Guess my number"; 
    while (notguessed) 
    { 
     cin >> guess; 
     if (guess == number) 
     { 
      cout << "You got it" << endl; 
      notguessed = false; 
     } 
     if (guess < number) 
     { 
      cout << "To low try again" << endl; 
     } 
     if (guess > number) 
     { 
      cout << "To high try again" << endl; 
     } 
    } 
    return 0; 
} 

你試圖輸入一個字符串 「猜測」。將其改爲cin >>猜測。 並更改while循環分號。

0
cin >> "Guess"; 

應當符合

cin >> guess; 
0

做出改變10 while循環使用; 刪除; 提供一些 而(條件){//做代碼}符合

做出改變13

you mistakenly "" 
it means string 
you need variable 
String guess; 
cin >> guess; 
相關問題