用C++实现输入n个整数,输出大于等于平均数的整数
时间: 2024-09-08 09:03:11 浏览: 58
在C++中,为了实现输入n个整数并找出大于等于平均数的整数,你需要首先读取所有数字,然后计算它们的平均值,并遍历数组以找出满足条件的数字。以下是一个简单的例子:
```cpp
#include <iostream>
#include <vector>
double calculateAverage(const std::vector<int>& numbers) {
double sum = 0;
for (int num : numbers) {
sum += num;
}
return sum / numbers.size();
}
std::vector<int> findGreaterNumbers(std::vector<int>& nums) {
double avg = calculateAverage(nums);
std::vector<int> result;
for (int num : nums) {
if (num >= avg) {
result.push_back(num);
}
}
return result;
}
int main() {
int n;
std::cout << "请输入整数的数量(n): ";
std::cin >> n;
std::vector<int> numbers(n);
std::cout << "请输入" << n << "个整数: ";
for (size_t i = 0; i < n; ++i) {
std::cin >> numbers[i];
}
std::vector<int> greaterNumbers = findGreaterNumbers(numbers);
if (greaterNumbers.empty()) {
std::cout << "没有数字大于等于平均数。\n";
} else {
std::cout << "大于等于平均数的整数有: ";
for (int num : greaterNumbers) {
std::cout << num << " ";
}
std::cout << "\n";
}
阅读全文