0
Follow
0
View

**C++** How to write the value of a one-dimensional array?

duguqiangwei 注册会员
2023-02-28 04:35

#include 
using namespace std;
int main() {
    int n,b;
    cin>>n;
    int a[n],sum=0;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];    
    }
    for(int i=0;i<n;i++) 
    {
          sum+=(i%4+1)*a[i];   
    }
    cout<<sum<0;
}

cuibojason 注册会员
2023-02-28 04:35

This answer quotes ChatGPT


#include 
using namespace std;

int main() {
    int n;
    cin >> n;

    int a[n];
    for(int i=0; i> a[i];
    }

    int sum = 0;
    for(int i=0; iif((i+1)%4 == 1 || (i+1)%4 == 2) {
            sum += a[i] * (i%4 + 1);
        } else {
            sum += a[i];
        }
    }

    cout << sum << endl;

    return 0;
}

First input the length of the array n and n integers, and then calculate the value of the array according to the requirements of the question, that is, multiply each element with the corresponding coefficient according to the law, and then add up to get the value of the array. The rule is: the first digit of the array is multiplied by 1, the second digit by 2, the third digit by 3, the fourth digit by 4, the fifth digit by 1, the sixth digit by 2, the seventh digit by 3, the eighth digit by 4, and so on.

The

code uses a for loop, which first creates an array a based on the length of the array, and then reads n integers to store in the array A. Then in the second for loop, the value of the array is calculated according to the rule, and the corresponding coefficient is determined according to the index of the element in the array. Finally output the value of the array.

, for example, for the sample input, the array has a value of 1 * 1 + 2 * 2 + 3 * 3 + 4 * 4 + 5 * 2 + 1 + 6 7 * 3 + 8 * 4 + 9 * 1 + 10 * 2 = 129, so the output 129.

dazui9813 注册会员
2023-02-28 04:35
cuikaick11 注册会员
2023-02-28 04:35
int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int sum = 0; for (int i = 0; i < n; i++) { if ((i + 1) % 4 == 1) { sum += arr[i]; } else if ((i + 1) % 4 == 2) { sum += 2 * arr[i]; } else if ((i + 1) % 4 == 3) { sum += 3 * arr[i]; } else if ((i + 1) % 4 == 0) { sum += 4 * arr[i]; } } cout << sum << endl; return 0; } .
< !- - - - - >

About the Author

Question Info

Publish Time
2023-02-28 04:35
Update Time
2023-02-28 04:35