
一个C++程序,用于在给定的正整数数组中找到出现奇数次数的数字。在这个数组中,所有数字都出现偶数次。
Input: arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7}
Output: 7使用两个循环,外部循环逐个遍历所有元素,内部循环计算外部循环遍历的元素出现的次数。
#include <iostream>
using namespace std;
int Odd(int arr[], int n){
for (int i = 0; i < n; i++) {
int ctr = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
ctr++;
}
if (ctr % 2 != 0)
return arr[i];
}
return -1;
}
int main() {
int arr[] = {5, 7, 8, 8, 5, 8, 8, 7, 7};
int n = 9;
cout <<Odd(arr, n);
return 0;
}以上就是查找出现奇数次数的数字的C/C++程序的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号