2017-04-11 102 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; 
}