Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

c++ - Algorithm crashing

int function(int A[], int n)
{

    int i = 0;
    int sum = 0;
    int amount = 0;

    while(i<n) {
        if(A[i] > 0) {
            sum=sum+A[i];
            amount++;
        }
        else {
            i++;
        }
    }
    while(!(i<n)) {
        if(ile>0){
            return sum/amount;
        } else {
            return 0;
        }
    }

}

I am generating random array of numbers between 0-10 , Im trying to use this with this algorithm, but all the time im getting result 6422260. Can someone tell me how should I approach this?

   int n;
    cin >> n;
    int arr[n];
    srand(time(NULL));

    for (int i = 0; i < 10; i++)
    {
     arr[i] = rand() % 10;
    }
    function(arr, n);

question from:https://stackoverflow.com/questions/65857506/algorithm-crashing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a solution to your problem:

#include <random>
#include <iostream>

void fill(int arr[]); 
int random(int from, int to);

using namespace std;

int main(void)
{
    int arr[10];
    fill(arr);
    for(int i = 0; i<10; i++)
        printf("%d ", arr[i]);
 
    return 0;
}

void fill(int arr[]){
    for(int i=0;i<(*(&arr + 1) - arr);i++){
        arr[i] = random(0, 10);//adjust accordngly
    }
}

int random(int from, int to){
    std::random_device dev;
    std::mt19937 rng(dev());
    std::uniform_int_distribution<std::mt19937::result_type> dist6(from, to); // distribution in range [from, to]
    return dist6(rng);
}

Your problem is you are not generating random numbers your algorithm is generating the same set of numbers! You need a logic to generate random number. Usually they are generated from system time ...

Attribution : https://stackoverflow.com/a/13445752/14911094


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...