C/C++编程学习 - 第11周 ② 求奇数的乘积

题目链接

题目描述

给你n个整数,求他们中所有奇数的乘积。

Input
输入数据包含多个测试实例,每个测试实例占一行,每行的第一个数为n,表示本组数据一共有n个,接着是n个整数,你可以假设每组数据必定至少存在一个奇数。

Output
输出每组数中的所有奇数的乘积,对于测试实例,输出一行。

Sample Input

3 1 2 3
4 2 3 4 5

Sample Output

3
15

思路

首先要判断给出的整数是否为奇数;其次是累乘。注意累乘的结果可能会很大,所以最好开long long保存。

C++代码:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n;
	while(cin >> n)
	{
    
    
		long long ans = 1, num;
		for(int i = 0; i < n; i++)
		{
    
    
			cin >> num;
			if(num & 1) ans *= num;
		}
		cout << ans << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44826711/article/details/113099931