DashOJ-8.奇偶统计

题目链接:

题目详情 - 奇偶统计 - DashOJ


思路:

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


代码:

cpp 复制代码
#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多香啊

cpp 复制代码
#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;
}
相关推荐
OOJO5 小时前
c++---list介绍
c语言·开发语言·数据结构·c++·算法·list
Amazing_Cacao7 小时前
深度观察 | 从“产区玄学”到“液态战场”:精品巧克力的终极试金石
学习
会编程的土豆7 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
张同学038 小时前
220V 转 12V/5V 电源输入电路设计笔记
笔记·嵌入式硬件·硬件工程
深蓝海拓8 小时前
S7-1500PLC学习笔记:MOVE_BLK、MOVE_BLK_VARIANT、BLKMOV的区别
笔记·学习·plc
darkhorsefly8 小时前
玩24算的益处
学习·游戏·24算
迈巴赫车主8 小时前
蓝桥杯19724食堂
java·数据结构·算法·职场和发展·蓝桥杯
6Hzlia8 小时前
【Hot 100 刷题计划】 LeetCode 78. 子集 | C++ 回溯算法题解
c++·算法·leetcode
所以遗憾是什么呢?9 小时前
【题解】Codeforces Round 1081 (Div. 2)
数据结构·c++·算法·acm·icpc·ccpc·xcpc
白藏y9 小时前
【C++】muduo接口补充
开发语言·c++·muduo