虽然我使用两个 cin 输入将数据输入到数组中,但第一个输入工作正常,但第二个数组输入正在获取任意值

问题描述

我正在尝试获取两个输入并将其保存到两个不同的数组中,但是第一个数组的输入被完美地存储但是第二个输入值是任意的我不明白为什么会这样

#include<iostream>
using namespace std;
int main()
{
    int n;
    int points = 20,fouls = 10;
    cin>>n;
    int arr[n],fls[n],pt[n],fl[n];
    for(int i = 0; i < n; i++){
        cin >> arr[i] >>fls[i];
    }
 
    for(int i = 0; i< n;i++){
        pt[i]= arr[i] * points;
        fl[i] = fls[i] * fouls;

        // arr[i] = arr[i] - fls[i];
        // cout<<pt[i]<<" ";
        cout<<fl[i]<<" ";

    }

    // int max = arr[0];
    // for(int i =1; i <n;i++){
    //     if(arr[i]>max){
    //         max = arr[i];
    //     }
    // }
    // cout<<max;
    return 0;
}

输出

Output of the code see how I am multiple the second array with 10 but the answer is wrong

解决方法

所写即所得。

在这个 for 循环中

for(int i = 0; i < n; i++){
    cin >> arr[i] >>fls[i];
}

您正在按顺序输入以下值

40 30 50 2 4 20

所以

arr[0] = 40 fls[0] = 30  // first iteration of the loop
arr[1] = 50 fls[1] = 2   // second iteration of the loop
arr[2] = 4  fls[2] = 20  // third iteration of the loop

然后在这个 for 循环中

for(int i = 0; i< n;i++){
    pt[i]= arr[i] * points;
    fl[i] = fls[i] * fouls;

    // arr[i] = arr[i] - fls[i];
    // cout<<pt[i]<<" ";
    cout<<fl[i]<<" ";

}

你会得到

fl[0] = 300,fl[1] = 20 fl[2] = 200

此输出显示在屏幕截图中。

请注意可变长度数组不是标准的 C++ 特性。您应该使用 std::vector<int>