我在打印反转号码时遇到困难。该算法正在按预期方式进行用户输入的反转,但无法正确显示:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << InValue << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
我该如何解决问题?
这应该做的工作。检查代码中的注释
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
int reverseVal = 0; // Add this variable to store the reverse number
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
// Add this to store
reverseVal = reverseVal*10 + rem;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << reverseVal << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
您尚未在任何地方存储反向变量,并且n == 0
是循环终止的时间。循环结束后打印n
时,如您所见,它必须为0。解决的办法是在分n
时存储余数。
这里有几个实现此目的的选项。
使用stringstream
:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int original_value, n;
stringstream ss;
cout << "Enter an integer >= 0:";
cin >> original_value;
n = original_value;
if (n < 0) {
n = -n;
ss << '-';
}
while (n > 0) {
ss << n % 10;
n /= 10;
}
cout << original_value << " in reverse is " << ss.str() << "\n";
return 0;
}
使用reverse
:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n = -1234;
string rev = to_string(n);
reverse(rev.begin() + (rev[0] == '-' ? 1 : 0), rev.end());
cout << rev << "\n";
return 0;
}
样品运行:
Enter an integer >= 0: -1234
-1234 in reverse is -4321
如果末尾需要整数,则始终可以使用parse it,atoi
或istringstream
从字符串中选择stoi
。