用户输入数字ex,7。然后返回该数字的所有倍数直到1000.X是用户输入。我有if / else if每个号码。会有不同的方法吗?
void printSeries()
{
if (x == 0)
{
cout << "Closing program" << endl;
}
else if (x == 1)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 1 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 2)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 2 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 3)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 3 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 4)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 4 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 5)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 5 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 6)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 6 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 7)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 7 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 8)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 8 == 0)
{
cout << "[" << x << "] ";
break;
}
x++;
}
}
else if (x == 9)
{
cout << "Printing numbers divisible by " << x << " between " << x << " and 1000" << endl;
while (x <= 1000)
{
while (x % 9 == 0)
{
cout << "["<< x << "] ";
break;
}
x++;
}
}
}
答案 0 :(得分:0)
cin >> x;
int counter = 1;
while ((x>0) && (true))
{
int multiple = x* counter;
if (multiple > 1000) break;
cout << multiple;
counter++;
}
答案 1 :(得分:0)
使用for
循环相当直接,因为这可以管理您的计数&#39;变化很好:
#include <iostream>
using namespace std;
int main() {
unsigned int x = 0;
cout << "Please enter a number (greater than 0): ";
cin >> x;
for (unsigned int i = 0; x * i < 1000; ++i)
cout << '\n' << x * i;
}
答案 2 :(得分:0)
你在找这样的东西吗?
#include <iostream>
int main() {
int x = 0;
std::cout << "Please input number: ";
std::cin >> x;
for (int i = 0; x*i < 1000; i++) {
std::cout << "[" << x*i << "]" << std::endl;
}
return 0;
}