为什么循环只在 c++ 中使用 rand() 函数时才运行 1 或 2 次

Why does loop runs 1 or 2 times only when I use rand() function in c++

本文关键字:函数 运行 循环 c++ rand 为什么      更新时间:2023-10-16

我想为我的程序生成随机测试用例,但它在运行 1 或 2 次后崩溃。我使用 rand(( 函数为随机测试用例生成随机数但它不会在一次或有时两次后运行。并且不生成任何随机数。程序只是退出。

#include<bits/stdc++.h>
#include<ctime>
#include <time.h>
using namespace std;
long long int naive(long long int arr[],long long int n){
    long long int max=-1;
    for(long long int i=0;i<n;i++)
    {
        for(long long int j=0;j<n;j++){
            if(arr[i]%arr[j] > max){
                max = arr[i]%arr[j];
            }
        }
    }
    return max;
}
long long int efficent(long long int arr[],long long int n){
    long long int max1=0,max2=0;
    for(long long int i=0;i<n;i++){
         if (arr[i] > max1) 
        { 
            max2 = max1; 
            max1 = arr[i]; 
        } 
        else if (arr[i] > max2 && arr[i] != max1) 
            max2 = arr[i]; 
    }
    return max2%max1;
}
int main(){
    srand(time(0));
    long long int count=0;
    int t=10;
    while(t--){
      long long int n;
      n = rand()%10;
      long long int arr[n];
      for(long long int i=0;i<n;i++){
        arr[i] = rand()%10;
      }
      long long int a,b;
      a = naive(arr,n);
      b = efficent(arr,n);
      if(a == b)
        cout<<"Naive : "<<a<<"tEfficent : "<<b<<"n";
      else{
        cout<<"nNot Equal."<<"nCount : "<<++count<<endl;
        cout<<"Naive : "<<a<<"tEfficent : "<<b<<"n";
      }
    }
    return 0;
}

除了内存泄漏和未正确声明另一个答案中提到的可变大小数组之外,问题是您正在对可能是 0 的值执行 mod 操作。 这将强制程序退出。 要解决此问题,请更改

arr[i] = rand()%10;

到类似的东西

arr[i] = rand()%10+1;

以防止除以 0。

编辑:正如@Michael Dorgan所提到的,您可能应该为n做同样的事情。改变

n = rand()%10;

n = rand()%10+1;

以防止分配 0 长度数组。

这段代码有问题:

while(t--){
    long long int n;
    n = rand()%10;
    long long int arr[n];
    for(long long int i=0;i<n;i++){
    arr[i] = rand()%10;
    }

如果您需要可变大小的数组,则应在while块的最后一个右大括号之前使用 long long int * arr = new long long int[n];delete[] arr;