DashOJ-8.奇偶统计

题目链接:

题目详情 - 奇偶统计 - DashOJ


思路:

(while循环加if分支语句)
巧用死循环 
while(1)
然后在里面第一句就判断输入的数字是否等于0 
 if(x==0)
,如果
等于0就直接break跳出循环
或者用
while(cin>>x)

代码:

#include<bits/stdc++.h>
using namespace std;

int main() {
	int sum=0,ans=0;
	int x;

	while(1) {
		cin>>x;
		if(x==0) {
			break;
		} else if(x%2==0) {
			sum++;
		} else if(x%2==1) {
			ans+=x;
		}
	}

	cout<<sum<<endl;
	cout<<ans<<endl;
	return 0;
}

错误代码:

原因:

不要这种写法,break多香啊

#include<bits/stdc++.h>
using namespace std;

int main() {
	int sum=0,ans=0;
	int x;
	while(cin.get()!=0) {
		cin>>x;
		if(x%2==0) {
			sum++;
		} else if(x%2==1) {
			ans+=x;
		}
	}
	cout<<sum<<endl;
	cout<<ans<<endl;
	return 0;
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>