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;
}
相关推荐
端平入洛16 小时前
auto有时不auto
c++
西岸行者2 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
starlaky2 天前
Django入门笔记
笔记·django
勇气要爆发2 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
悠哉悠哉愿意2 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
超级大福宝2 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
勇气要爆发2 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain