编程论坛
注册
登录
编程论坛
→
C++教室
随机输入两个四位正整数,将它们倒过来,然后求其和并输出。
shaine
发布于 2017-10-27 23:24, 3344 次点击
【问题描述】随机输入两个四位正整数,将它们倒过来,然后求其和并输出。
【输入形式】<正整数><空格><正整数><enter>
【输出形式】
【样例输入】2000 1903
【样例输出】3093
各位大神,有什么简洁的代码没 必须得一个数一个数的写吗?
3 回复
#2
陈氏
2017-10-28 22:12
#include<iostream.h>
void main()
{
int a,b,c,d,e,f;
cout<<"input a:";
cin>>a;
b=a/1000;
c=a%1000/100;
d=a%100/10;
e=a%10;
f=e*1000+d*100+c*10+b;
cout<<f<<endl;
}这是我刚学的,但是只能到一个数,你可以加一个循环。
[此贴子已经被作者于2017-10-28 22:15编辑过]
#3
蓝天绿水
2017-10-29 11:51
程序代码:
#include
<iostream.h>
using
namespace
std;
int
main ()
{
int
a,b,c,d;
cout
<<
"
请输入两个四位数字,并用空格隔开 :
"
<<endl;
cin
>> a >> b;
c = a %
10
*
1000
+ (a /
10
) %
10
*
100
+ (a /
100
) %
10
*
10
+(a /
1000
);
d = b %
10
*
1000
+ (b /
10
) %
10
*
100
+ (b /
100
) %
10
*
10
+(b /
1000
);
cout
<< c+d << endl;
return
0
;
}
这个测试过没有问题
#4
吸血虫
2017-11-06 14:23
鉴于编程中常用的是int类型,我把命题改成“两个整数”重作了一遍;
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
void conv(string& ins){
bool b=false;
if(!ins.empty()){
if( (ins[0]=='-')||(ins[0]=='+') )
b=true;
}
if(!b)
reverse(ins.begin(),ins.end());
else
reverse(++(ins.begin()),ins.end());
}
int main(void){
string s1,s2;
int n1,n2;
cout << "请输入两个整数,并用空格隔开 :"<<endl;
cin >> s1>>s2;
conv(s1);
conv(s2);
stringstream ss;
ss << s1 << " " << s2;
ss >> n1 >> n2;
if(!ss){
cout << "计算失败" << endl;
system("PAUSE");
return 1;
}
else {
//cout << n1 << " " << n2 << endl;
cout << n1+n2 << endl;
system("PAUSE");
return 0;
}
}
如果不想求整数,想求两个小数,只需要将程序中的 int 替换成 double 即可。
1