【发布时间】:2016-06-01 09:43:25
【问题描述】:
我目前正在开发一个程序,该程序输出第一个数字大于最后一个数字的三位整数的数字 1089(即幻数)。我输入了一些代码,但没有收到 1089,而是收到 891。谁能提供一些解释原因。
//Uses a cout to inform user will be using the number 412 as an example.
//Uses a cout to explain to user the number needs to be reversed.
cout << "Alright, let's walk through an example, using the number 412." << endl;
int numExample = 412;
cout << "Please input 412" << endl;
cin >> numExample;
cout << "First, the number 412 is reversed." << endl;
//The following is done for reversing the number 412:
int reverseNum = 0, remainder = 0;
while (numExample)
{
remainder = numExample % 10;
reverseNum = (reverseNum * 10) + remainder;
numExample = numExample / 10;
}
cout << "The reverse of 412 is " << reverseNum << endl;
cout << "Next, we want to subtract the reverse of the original number from its reverse" << endl;
cout << "This gives us 198" << endl;
cout << "From there, we want to reverse 198." << endl;
//The same procedure is used to reverse 198
int numExample2 = 198;
cout << "Please enter 198" << endl;
cin >> numExample2;
int reverseNum2 = 0, remainder2 = 0;
while (numExample2)
{
remainder2 = numExample2 % 10;
reverseNum2 = (reverseNum2 * 10) + remainder2;
numExample2 = numExample2 / 10;
}
cout << "The reverse of 198 is " << reverseNum2 << endl;
int magicNumber = (reverseNum2 + numExample2);
cout << "Following that, we want to add 891 to 189 which gives us " << magicNumber << endl;
【问题讨论】:
-
提示:
numExample2在while (numExample2)循环之后的值是多少? (如果您不知道,请打印出来。) -
我相信我在上面定义了它,但是
numExample2是一个等于 198 的 int。 -
真的吗?打印
reverseNum2后立即添加cout << numExample2 << endl;。并多想一下导致循环结束的原因。
标签: c++ magic-numbers