首页 > 解决方案 > 如何在数组中的所有最小值之后放置任何值 X?

问题描述

如果我输入array,首先代码会找到 ,minimums然后我想在所有最小值之后输入零。例如 given an array=1,1,3,1,1 我们看到1s是最小值,所以结果应该是 =1,0,1,0,3,1,0,1,0

代码

#include <pch.h>
#include <iostream>


int main()
{

    int min = 10000;
    int n;                                       
    std::cout << "Enter the number of elements (n): "; //no of elements in the 
    std::cin >> n;                                     //array

    int *array = new int[2 * n];
    
    std::cout << "Enter the elements" << std::endl;



    for (int i = 0; i < n; i++) {                      
        std::cin >> array[i];
        if (array[i] > min)
            min = array[i];
    }

    for (int i = 0; i < n; i++) {                

        if (array[i] == min) {                   // Not very clear about this
            for (int k = n; k > i; k--)          // part of the code, my teacher
                 array[k] = array[k - 1];        //explained it to me , but i 
             array[i + 1] = 0;               // didn't understand (from the      
             i++;                            // `for loop k` to be precise)
             n++;
        }
        std::cout << array[i] << ", 0";
    }
        
                                  
    
    return 0;
}

但我的回答并没有在最小值之后完全置零

标签: c++arraysc++11jagged-arrays

解决方案


第一个问题是计算min:<而不是>.

如果您正在修改参数in在循环内部,则会出现另一个问题。这是相当危险的,意味着要非常谨慎。

另一个问题是它应该i++; n++;代替i--,n--;

这是代码:

//  #include <pch.h>
#include <iostream>


int main()
{
    int min = 1000000;
    int n;                                       
    std::cout << "Enter the number of elements (n): "; //no of elements in the 
    std::cin >> n;                                     //array

    int *array = new int[2 * n];

    std::cout << "Enter the elements" << std::endl;

    for (int i = 0; i < n; i++) {                      
        std::cin >> array[i];
        if (array[i] < min)
            min = array[i];
    }

    for (int i = 0; i < n; i++) {                
        if (array[i] == min) {                   // Not very clear about this
            for (int k = n; k > i; k--)          // part of the code, my teacher
                 array[k] = array[k - 1];        //explained it to me , but i 
            array[i + 1] = 0;               // didn't understand (from the)      
            i++;
            n++;
        }
    }

    for (int i = 0; i < n; i++) {                
        std::cout << array[i] << " ";
    }
    std::cout << "\n";

    return 0;
}

推荐阅读