1005: 求和

题目链接:http://oj.ecustacm.cn/problem.php?id=1005

题目描述

给出一串的数,请计算它们的和。

输入

输入只有一行,包含若干个数,数之间用空格隔开。数字和答案保证在int范围内。 

输出

求这些数的和。

样例输入 Copy

1 6 -9 6 5

样例输出 Copy

9


题意:就是不停的读入数字,用空格分开,回车后停止读入。
思路:接受住空格和回车,只要数字累加到结果上,判断输入字符为回车时结束输入。
注意:要用getchar()读入字符,cin会错。

代码如下:
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int n,sum=0;
 6     char c;
 7     while(cin>>n)
 8     {
 9         c=getchar();
10         //cout<<"n="<<n<<endl;
11         //cout<<"c="<<c<<endl;
12         sum+=n;
13         if(c=='\n')
14             break;
15 
16         //cout<<"sum="<<sum<<endl;
17     }
18     cout<<sum<<endl;
19     return 0;
20 }

Keafmd

加油!

一起努力!

 

 
posted @ 2020-06-20 15:47  牛哄哄的柯南  阅读(256)  评论(0编辑  收藏  举报