我正在尝试打印用户输入的整数的最后一位数字。例如,如果用户输入5432,我的输出是2 32 4325432。我设法使用while循环为此编写了代码,但是我不明白为什么我的循环没有终止,请帮助我终止它吗?
void main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input % modulu; // test checks if all the number has been printed
//disect number
while (test > 0);
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = input % modulu;
}
}
您的第一个问题在这里:
while (test > 0);
该;
终止while语句和代码将留在同时永远。换句话说,以下所有代码都不会执行。去除那个;
第二个问题是处理方式test
-不要取模,而是除以10。像这样:
int main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input; // <------------- Just make test equal to the input
while (test > 0) // <------------- The ; removed
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = test / 10; // <----------- Divide by 10
}
return 0;
}
请注意,上面的代码在零方面存在一些问题,例如1001
将输出1
1
1
1001
而不是1
01
001
1001
。
您可以使用一种完全不同的方法来解决此问题,string
而不是int
喜欢:
int main()
{
//declare variables
string input;
//read input from user
cout << "Please enter a number: ";
cin >> input;
cout << input << endl;
int size = input.size();
int tmp = size;
while (tmp >= 0)
{
for (int t = tmp; t < size; t ++) cout << input[t];
cout << endl;
--tmp;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句