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;
}
相关推荐
石像鬼₧魂石4 小时前
HexStrike-AI人工智能 渗透测试学习(Metasploitable2 192.168.1.4)完整流程总结
学习·ubuntu
非凡ghost4 小时前
MusicPlayer2(本地音乐播放器)
前端·windows·学习·软件需求
大数据追光猿5 小时前
【大数据Doris】生产环境,Doris主键模型全表7000万数据更新写入为什么那么慢?
大数据·经验分享·笔记·性能优化·doris
sevenez5 小时前
Vibe Coding 实战笔记:从“修好了C坏了AB”到企业级数据库架构重构
c语言·笔记·数据库架构
智嵌电子5 小时前
【笔记篇】【硬件基础篇】模拟电子技术基础 (童诗白) 第10章 模拟电子电路读图
笔记·单片机·嵌入式硬件
蓝桉~MLGT5 小时前
Ai-Agent学习历程—— 阶段1——环境的选择、Pydantic基座、Jupyter Notebook的使用
人工智能·学习·jupyter
2301_800050995 小时前
mysql
数据库·笔记·mysql
阿闽ooo5 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
QT 小鲜肉6 小时前
【Linux命令大全】001.文件管理之mmove命令(实操篇)
linux·服务器·前端·chrome·笔记
不会学习?6 小时前
markdown笔记分享
经验分享·笔记