2017-04-11 99 views
-3

我試圖讓這段代碼的工作:C++做while循環不工作

#include <iostream> 

using namespace std; 

int main() 
{ 

int i; 
do 
{ 
    cout << ("please enter a number between 1 and 10"); 
    cin >> i; 

} while(i > 10 && i < 1) 
    cout << "the square of the number you have entered is " << i*i; 
} 

基本上,這個想法是,用戶輸入1和10之間的數字雖然數目不是1之間10,它一直要求用戶在這些值之間輸入一個數字。然後,當數字在這些值之間時,它被平方並返回給用戶。

我不明白爲什麼這不工作

任何幫助表示讚賞

+1

將條件從「和」更改爲「或」。 – Meccano

+0

請仔細考慮一下您的代碼。 –

+5

我怎麼能同時大於10和小於1? –

回答

2

您有:

while (i > 10 && i < 1) 

你想:

while (i > 10 || i < 1) 
+0

或者也許'while(i> 1 && i <10)'來簡化你的邏輯...... – cbuchart

+0

考慮爲OP添加一個描述 –

0

您應該使用一個或||,條件與&&永遠不會成立。

0
while (i > 10 && i < 1) 

您的狀況在邏輯上是有缺陷的;如果重新詮釋,它說:

i大於10 i小於1

從你的代碼來看,||經營者應使用:

} while (i > 10 || i < 1); 
0

正如其他人所述,您的狀況有問題。 一個數字不能明顯低於1並且高於10,所以while循環在do語句後立即退出。

#include <iostream> 

using namespace std; 

int main() 
{ 

    int i; 
    do 
    { 
     cout << ("please enter a number between 1 and 10"); 
     cin >> i; 

    } while (i < 1 || i > 10) 

    cout << "the square of the number you have entered is " << i*i; 
} 
0

循環條件是錯誤的,絕不會環,如圖i不能小於1 &&同時大於10。您應該使用邏輯OR(||)運算符。另外,在do-while語句之後必須有一個分號。而且你可能想在提示符後面放置行尾。此外,你不想開始污染全局命名空間的壞習慣,即使有std的迷人之處。因此:

#include <iostream> 

int main() 
{ 
    int i; 
    do { 
     std::cout << "please enter a number between 1 and 10\n"; 
     std::cin >> i; 
    } while (i > 10 || i < 1); 

    std::cout << "the square of the number you have entered is " << i*i << std::endl; 
}