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;
}
相关推荐
Pandora_41734 分钟前
cursor学习
学习
程序喵大人38 分钟前
推荐个 C++ 练习平台
开发语言·c++·工具推荐
zhdy567891 小时前
最简单方法 设置matlab坐标轴刻度标签的字号,设置坐标轴标题和图形标题,并指定字号。画出的图片背景设置为白色,
笔记
崇山峻岭之间1 小时前
Matlab学习笔记02
笔记·学习·matlab
木木em哈哈1 小时前
C语言多线程
笔记
fpcc1 小时前
跟我学C++中级篇——std::is_invocable的分析应
c++
Kiri霧2 小时前
Range循环和切片
前端·后端·学习·golang
Code Slacker3 小时前
LeetCode Hot100 —— 滑动窗口(面试纯背版)(四)
数据结构·c++·算法·leetcode
hssfscv3 小时前
Javaweb 学习笔记——html+css
前端·笔记·学习