gpt4 book ai didi

C++ 整数数组转换和操作

转载 作者:行者123 更新时间:2023-11-28 04:03:07 30 4
gpt4 key购买 nike

所以我有一个任务要

  • 输入一个数组,
  • 计算它的偶数(正数和负数),
  • 计算所有偶数的总和#
  • 在程序必须输出一个转换后的数组后,其中每个偶数 # 都变成它前面所有数字的总和(** 在原始数组 ** 中):arr[i] = 1, 2, 3, 4, 5, 6; -> array[i] = 1, 1, 3, 6, 5, 15

所以我是这样尝试的,但它一直工作到第 5 个元素,之后它开始输出一些看起来很奇怪的 #s。我该怎么办???

#include <iostream>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <locale>
#include <algorithm>

using namespace std;

int main()
{
srand((unsigned)time(NULL));
int n, i, k = 0;
int sum;
int S = 0;
cout << "What size array would you like:" << endl;
cout << "n = ";
cin >> n;
int* A = new int[n];
sum = 0;
cout << "Input elements: ";
for (i = 0; i < n; i++) cin >> A[i];
for (int i = 0; i < n; i++)
{
cout << A[i] << " ";
}
cout << endl;
cout << endl;
for (int i = 0; i < n; i++)
{
if (A[i] % 2 == 0) {
k = k + 1;
sum += A[i];
}
}
cout << "Ampount of even numbs: " << k << endl << endl;
cout << "Sum of even numbs: " << sum << endl << endl;
cout << "New array: " << endl;
for (int i = 0; i < n; i++)
{
if (abs(A[i]) % 2 == 0)
{
for (int j = 0; j < i; j++)
{
S += A[j];
}
A[i] = S;
}
}

for (int i = 0; i < n; i++)
{
cout << A[i] << " ";
}
cout << endl;
cout << endl;
}

最佳答案

好吧,你说的是 C++ 和“有趣”,所以这里有一个更 C++ 的方法来给这只猫换皮。 .

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;

int main() {
vector<int> v = {1,2,3,4,5,6};
const auto isEven = [](int x){return x%2==0;};
const auto print = [](const int& n) { cout << " " << n; };

cout << "Before: "; for_each(v.begin(), v.end(), print); cout << endl;
cout << "Num Even: " << count_if(v.begin(), v.end(), isEven) << endl;
cout << "Sum Even: " << accumulate(v.begin(), v.end(), 0, [isEven](auto acc, int e) { return acc + (isEven(e) ? e : 0); }) << endl;
// I'm not guru enough for Jarod42s c++20 voodoo 🤯nor is IDEONE 😉
int b=0;
vector<int> v2;
for (auto& x : v) {
isEven(x) ? v2.push_back(b) : v2.push_back(x);
b+=x;
}
cout << "Transformed: "; for_each(v2.begin(), v2.end(), print); cout << endl;

return 0;
}

在这里尝试 https://ideone.com/jDjoeB

关于C++ 整数数组转换和操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59176333/

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