嗨,这是我的问题。
编写一个使用do-while语句的程序。它读取整数 n来自键盘。如果n不在1到10的范围内,则会发出声音 “嘟嘟”并要求另一个整数。如果n在正确的范围内,则写入 输出“你有输入n”然后退出。
这是我的答案。
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
do
{
cout << "Enter an integer." << endl;
cin >> number;
if (!(number >= 1 && number <= 10))
{
Beep(400, 400);
}
}
while (!(number >= 1 && number <= 10));
cout << "You have input " << number << endl;
system("PAUSE");
}
你可以看到
行(!(number >= 1 && number <= 10))
重复。有没有解决方法呢?
答案 0 :(得分:3)
int GetNumber()
{
int number;
cout << "Enter an integer." << endl;
cin >> number;
return number;
}
void main()
{
int n = GetNumber();
while(n < 1 || n > 10)
{
Beep(400, 400);
n = GetNumber();
}
cout << "You have input " << n << endl;
system("PAUSE");
}
答案 1 :(得分:1)
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
bool invalid_input = true;
do
{
cout << "Enter an integer." << endl;
cin >> number;
invalid_input = !(number >= 1 && number <= 10);
if (invalid_input)
{
Beep(400, 400);
}
}
while (invalid_input);
cout << "You have input " << number << endl;
system("PAUSE");
}
答案 2 :(得分:1)
...也许
int number = 0;
while (true)
{
cout << "Enter an integer." << endl;
if (cin >> number && number >= 1 && number <= 10)
break;
Beep(400, 400);
}
cout << "You have input " << number << endl;
system("PAUSE");