【问题标题】:the output array shows only the last element instead of inserting data at specified location in the array输出数组仅显示最后一个元素,而不是在数组中的指定位置插入数据
【发布时间】:2021-12-28 10:38:13
【问题描述】:
#include <iostream>
using namespace std;

#define max 10

int main()
{
    int items[max];
    int i,n,ub,location,data;

    cout<<"Enter the number of items you want to enter: "<<endl;
    cin>>n;

    ub=n-1;

    if(ub>=max-1){
        cout<<"Array is full!"<<endl;
    }

    else{
        cout<<"Enter "<<n<<" elements:"<<endl;
        for(i=0;i<n;i++){
            cin>>items[n];
        }

        cout<<"Enter the location where you want to insert:"<<endl;
        cin>>location;
        cout<<"Enter the data you want to insert in location "<<location<<endl;
        cin>>data;

        while(ub>=location){
            items[ub]=items[ub-1];
            ub--;
        }

        items[location]=data;

        cout<<"The array after insertion is as follows: "<<endl;
        for(i=0;i<n;i++){
            cout<<items[n]<<endl;
        }
    }

}

对于 n=5 的输入数组,假设为 {1 ,2 ,3 ,4 ,5 },我想在数组的位置 2 插入 data=19,使得输出为 {1,19,3 , 4, 5} 但我得到的输出是 {5 ,5 ,5 ,5 ,5}。我该如何解决这个问题?

【问题讨论】:

  • 当粘贴结果更相关时,请避免发布图片。这里的做法不好。
  • cin&gt;&gt;items[n]; 和后面对应的输出是错误的。使用[i]

标签: c++ arrays


【解决方案1】:

你有两个问题:

  1. cin&gt;&gt;items[n]; 必须是 cin&gt;&gt;items[i];
  2. cout&lt;&lt;items[n]&lt;&lt;endl; 必须是 cout&lt;&lt;items[i]&lt;&lt;endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 2014-11-01
    • 2018-10-30
    • 2019-10-22
    • 1970-01-01
    • 2021-08-14
    相关资源
    最近更新 更多