gpt4 book ai didi

c++ - 在 C++ 中打印一个数组

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:49 26 4
gpt4 key购买 nike

我正在尝试做一些 C++ 作业,但我似乎遇到了问题。我需要让用户输入 8 个数字,然后将 8 个数字存储在一个数组中。然后,如果其中一个数字大于 21,则输出该数字。代码在下面,有点草率。是的,这里是第一年 C++ 学习者 :p

#include <iostream>
using namespace std;

int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21

// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;


for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}

for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;

// Determine sum
sumVal = 0;

for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}

cout << "Sum: " << sumVal << endl;

return 0;
}

最佳答案

不要重新发明轮子,use standard algorithms :

std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });

我也改进了你程序的其余部分:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

auto constexpr count = 8;

int main() {
std::vector<int> numbers(count);

std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());

std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });

auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';

return 0;
}

查看live on Coliru !

关于c++ - 在 C++ 中打印一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26411658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com