【发布时间】:2022-11-13 17:28:33
【问题描述】:
#include<iostream>
using namespace std;
class sample{
int x,y;
public:
void rev();
};
void sample::rev(){
cout<<"Enter a no:";
cin>>x;
int r,n;
while(x!=0){
r=x%10;
n=n*10+r;
x=x/10;
}
cout<<n;
}
int main(){
sample A;
A.rev();
return 0;
}
如果我输入一个数字,如:10,它需要给我rev no:01,但它只给1......我该如何解决?
【问题讨论】:
-
整数不能保留前导 0 的数量。它不会以任何方式存储在 int 中。整数始终是固定位数。对于前导 0,您必须自己考虑并在输出中处理它:https://stackoverflow.com/questions/1714515/how-can-i-pad-an-int-with-leading-zeros-when-using-cout-operator
-
将结果存储在字符串中。
-
@drescherjm 虽然正确,但仍然可以使用整数执行此操作。
-
01、1,甚至000001都是相等的。数字没有前导零。 -
在使用它之前不要初始化 n -> 因此未定义的行为
标签: c++