用戶輸入一個數字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