我应该写一个程序,它会要求用户输入一个数字,然后显示从1开始到输入数字^ 2的所有完美正方形。我写过这个程序,但是我被要求把它放在一个嵌套循环中。问题是,我不知道如何将其转换为嵌套循环格式。有没有人有任何想法?
到目前为止,这是我的计划:
int input;
int number = 1;
cout << "Enter a number: ";
cin >> input;
if(input > 1) {
cout << "The perfect squares are: ";
do {
cout << number*number;
number++;
input--;
if(input == 1) {
cout << " and "; }
else {cout << ", ";}
}while(input > 1);
cout << number*number << ".";
}
else if(input == 1) {
cout << "1";
}
else {
cout << "None.";
}
答案 0 :(得分:1)
为什么它需要是一个嵌套循环?这可以使用简单的for
循环来完成。
unsigned int input;
cout << "Enter a number: ";
cin >> input;
for (unsigned int i = 1; i <= input; ++i)
{
cout << i << " squared is " << i * i << endl;
}
while
循环等效项
unsigned int input;
cout << "Enter a number: ";
cin >> input;
unsigned int i = 1;
while(i <= input)
{
cout << i << " squared is " << i * i << endl;
++i;
}