我是编程的新手,正在寻找一些指导。我无法打印反向号码。该算法正在按预期工作,以反转用户的输入但无法正确显示:
#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;
}
使用反向:
#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
如果你需要一个整数,你可以使用atoi,istringstream或stoi从字符串中始终使用parse it。