无法在C++中显示反转的数字

Unable to display a reversed number in C++

本文关键字:数字 显示 C++      更新时间:2023-10-16

我在打印反向数字时遇到困难。该算法按预期工作,用于反转用户的输入,但无法正确显示:

#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

如果末尾需要一个整数,则可以始终使用atoiistringstreamstoi从字符串中解析它。