用户输入一个数字ex,7.然后返回该数字的所有倍数,直到1000. X是用户输入。如果每个号码都有if/else。会有不同的方式来做到这一点?什么是最佳方式将其重写成简单的
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++;
}
}
}
可被x整除的数字也是x的倍数。你不能使用这种关系吗? – Nandu