【发布时间】:2021-09-25 01:18:35
【问题描述】:
我正在尝试编写一个 C++ 程序来显示低于某个数字的所有礼貌数字。例如,如果有人要输入 6,那么我想打印出 3、5、6。如果要输入数字 9,我想打印出 3,5,6,7,9。
我已经完成了两个 for 循环。我只是不知道如何测试所有连续数字组合,以获得礼貌的数字。
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
cout << "Welcome to the polite numbers program." << endl;
int upValue;
int num1, num2;
cout << "What is the upper value? "; //Ask user for upper limit
cin >> upValue; //Stores user input into upValue
while (upValue < 1) //Validate user input of upper limit
{
cout << "What is the upper value? (must be an integer > 0) ";
cin >> upValue;
}
for (num1 = 1; num1 <= upValue; num1++) { //Looping from 1 to upper variable
for (num2 = num1 + 1; num2 <= upValue; num2++) { //Looping from 2 to upper
//Something goes here to get all polite numbers below a certain number.
}
}
return 0;
}
【问题讨论】:
-
将问题分解为更小的子问题。 IE。创建一个函数来测试一个数字是否礼貌
bool is_polite(int)。然后检查所有数字 1-upValue 是否有礼貌。