首页 > 编程语言 > 详细

[华为机试]求出数组中全部奇数之和以及全部偶数之和

时间:2016-01-14 08:32:52      阅读:234      评论:0      收藏:0      [点我收藏+]

技术分享

代码:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

int main()
{
	int num[100];
	int odd = 0, even = 0;

	std::string str;
	getline(std::cin, str);
	std::stringstream s(str);
	int j = 0;
	while(getline(s, str, ','))
	{
	        //考虑了字符串中有非数字的情况(不考虑貌似也对了)
		int count = 0;
		for (int i = 0; i < str.size(); i++)
		{
			if(str[0] == '-')
			{
				neg = true;
			}
			if (str[i] >= '0' && str[i] <= '9')
			{
				count++;
			}
		}
		if (count != str.size() && !neg)
		{
			continue;
		}
		if( neg && count != str.size() - 1 )
                {
			neg = false;
			continue;
		}
		num[j] = atoi(str.c_str());
		if (num[j] % 2 == 0)
		{
			even  += num[j];
			j++;
		}
		else
		{
			odd += num[j];
			j++;
		}
	}	
	std::cout<<odd <<","<< even;
}


[华为机试]求出数组中全部奇数之和以及全部偶数之和

原文:http://www.cnblogs.com/lcchuguo/p/5129088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!