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;
}
相关推荐
不想写代码的星星2 小时前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
齐生117 小时前
iOS 知识点 - 渲染机制、动画、卡顿小集合
笔记
用户962377954481 天前
VulnHub DC-1 靶机渗透测试笔记
笔记·测试
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
齐生12 天前
iOS 知识点 - IAP 是怎样的?
笔记
tingshuo29173 天前
D006 【模板】并查集
笔记
tingshuo29174 天前
S001 【模板】从前缀函数到KMP应用 字符串匹配 字符串周期
笔记
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星5 天前
虚函数表:C++ 多态背后的那个男人
c++