C ++中的数组问题

时间:2013-11-28 17:23:38

标签: c++ turbo-c++

我正在使用Turbo c ++
我需要将包含0的所有元素向左移动 如果数组包含以下值20 10 15 7 4 20 2
输出必须是这样的 - 0 0 0 10 15 4 2

完整的问题是第一部分是将用户输入的数字替换为0,所以我输入20并将它们替换为0.
原始值 - > 10 | 20 | 15 | 4 | 20 | 2 | 20
我编写了一个代码,用于搜索和替换输出为10 |的值0 | 15 | 4 | 0 | 2 |现在我需要在左侧收集这些0,意思是这个0 | 0 | 0 | 10 | 15 | 4 | 2

代码也包括我写的 -

#include<iostream.h>
#include<conio.h>
void main()
{
    int A[100],no,val,found;
    clrscr();
    cout<<"Enter number of elements you want to insert ";
    cin>>no;
    for(int i=0;i<no;i++)
    {
        cout<<"Enter element "<<i+1<<":";
        cin>>A[i];
    }

    cout<<"Enter the number you want to search ";
    cin>>val;

    for(int j=0; j<no; j++)
    {
        if(A[j]==val)
            A[j]=0;
    }

    for(int k=0; k<no; k++)
    {
        cout<<A[k]<<"   ";
    }
    getch();
}

需要一些帮助。

1 个答案:

答案 0 :(得分:1)

以下是我的建议:

  1. 不需要#include <conio.h>,而且它是特定于平台的。
  2. clrscr()函数调用会让人们试图帮助您 先前的文字被删除。
  3. 需要根据容量检查no变量 阵列。
  4. 尝试使用std::cin.ignore(10000, '\n');代替getch()
  5. 要将插槽移动为0,您需要将值从旧位置复制到新位置,其中第一个新位置为零位置。

    假设:

    0 -->|10|  
    1    |15|  
    2    | 0|  
    3    | 3|  
    4    | 4|  
    

    第一次迭代,将插槽2中的0与插槽2中的15交换:

    0 -->|10|  
    1    |15| --> | 0|
    2    | 0| --> |15|  
    3    | 3|
    4    | 4|
    

    第二次迭代,将插槽1中的0与插槽0中的10交换:

    0 -->|10| --> | 0|  
    1    | 0| --> |10|
    2    |15| 
    3    | 3|
    4    | 4|
    

    继续迭代直到上一个插槽的值为零或前一个插槽位于数组的开头之前。

    提示:您需要两个索引,现在和之前。

    编辑1:示例代码

    int swap_index = 0;  
    int search_index = 0;  
    #define MAX_NUMBERS 6
    unsigned int numbers[6] = {10, 15, 0, 3, 4};
    for (search_index = 0; search_index < MAX_NUMBERS; ++search_index)
    {
      if (numbers[search_index] == 0)
      {
        swap_index = search_index - 1;
        while (swap_index > 0)
        {
          numbers[swap_index + 1] = numbers[swap_index];
          numbers[swap_index] = 0;
          --swap_index;
        }
      }
    }
    

    此代码是基础。存在诸如限制检查之类的问题,这是读者需要解决的问题。