2070:【例2.13】数字对调时间限制: 1000 ms 内存限制: 65536 KB 提交数: 13801 通过数: 5972 【题目描述】输入一个三位数,要求把这个数的百位数与个位数对调,输出对调后的数。 【输入】三位数。 【输出】如题述结果。 |
分析:这道题目咋一看很简单,只要单独求出每个位的数字即可:
于是我很得意地写出了这个代码:
#include <iostream>
using namespace std;
int main(){
int a, b, c, d;
cin >> a;
b = a / 100;
c = (a % 100) / 10;
d = a - 100*b - 10*c;
cout << d << c << b;
}
结果:
😂
后来仔细想想,原来是错在没有考虑到:当个位为0时,是不能放到百位的,不然数据直接无意义。
正确答案:
#include<iostream>
using namespace std;
int main()
{
int a, s1, s2, s3;
cin >> a;
s1 = a / 100;
s2 = (a / 10) % 10;
s3 = a % 10;
if (s3 != 0)
{
cout << s3 << s2 << s1;
}
else if (s3 == 0 && s2 != 0)
{
cout << s2 << s1;
}
else
{
cout << s1;
}
}