質問

Trying to calculate max and minimum values of random numbers in arrays, I am not sure what I am doing wrong here. I have been trying to figure it out and I am at my wits end. Maybe one of you can help?

#include <iostream>
#include <stdlib.h>   
#include <ctime>

using namespace std;

int main() {
    int *sora;
    int num;
    int min;
    int max;

    cout<< "Enter the size :  " ;
    cin >> num;
    cout<< endl;
    sora = new int [num];   

    max= sora[0];
    min= sora[0];

    srand((unsigned)time(0));

    for(int x=0;x<num; x++) {
        sora[x]=rand()%100;

        if(min > sora[x]) {
            min=sora[x];        
        }
        else if (max < sora[x]) {
            max=sora[x];
        }

        cout<< sora[x] << endl;     
    }

    cout<< "Maximum value is: " << max << endl << "Minimum value is: " << min;
}
役に立ちましたか?

解決

if(min > sora[x]) {
    min=sora[x];
}
else if (max < sora[x])
{
    max=sora[x];
}

has the problem. The second else if statement is entered only if the first if is satisfied. But the second if has to be executed always. Please change the above block as follows

if(min > sora[x]) {
    min = sora[x];
}
if (max < sora[x]) {
    max = sora[x];
}

And you are also using an uninitialized area to compare against. If you are using only positive numbers

max = 0;
min = UINT_MAX;

If you use negative numbers also, then

max = INT_MIN;
min = INT_MAX;

You have to include <limits.h> for these macros.

他のヒント

You're initializing min and max to an undefined value when you do max= sora[0]; and min= sora[0];

Also, you have an else where you don't necessarily want one. The first value will be both the min and the max. You can start by setting max=0 and min=99, and that should solve that particular problem.

sora = new int [num];   

max= sora[0];
min= sora[0];

This line initializes a int array with garbage, and sets max and min to garbage values.

You have two options:

  1. At start initialize max to the lowest value possible (INT_MIN) and initialize min to the highest value possible (INT_MAX).

  2. First create a random value and assign it at sora[0] and initialize max and min to this value. After that initialize [1..num]

You are reading an uninitialized memory location:

sora = new int [num];   

max= sora[0];
min= sora[0];

Creating the array with new does not initialize its contents.

This causes what's known as undefined behavior, meaning almost anything can happen. In this case, it's probably pretty vanilla: some arbitrary value (most likely outside the 0-99 range of rand()%100) gets stored in min and max, very often leading to incorrect results.

Instead, do

// must #include <limits>

int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max();

or even just

int max = 0;
int min = 99;

since your range is predefined.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top