为什么循环只在 c++ 中使用 rand() 函数时才运行 1 或 2 次
Why does loop runs 1 or 2 times only when I use rand() function in c++
我想为我的程序生成随机测试用例,但它在运行 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;
。
相关文章:
- 如何在函数运行时逐个显示列表项
- C++:链接库两次,全局构造函数运行两次吗?
- C 从类的构造函数运行Boost线程
- 回文过滤器,函数运行良好,但main()无法编译
- 如何在 c++ 中将机器代码作为函数运行
- 将 PHP 中的 $_POST 变量传递给由 exec() 函数运行的C++程序
- 如何在 C++ 中使用一个 System() 函数运行 2 个命令
- 为什么用空函数运行std::线程会花费大量内存
- 在函数运行时停止 Wt C++函数
- C 构造函数运行时/编译时间
- 是否可以在析构函数运行时不销毁 obj
- CArray的析构函数运行大约需要30秒
- 如何使这个递归函数运行得更快
- 如何在Visual studio C++中检查函数运行时间
- C++函数运行,即使它不应该运行?
- 参数的可变数量函数运行时错误
- boost::asio::io_service析构函数运行很长时间
- 具有变量参数的函数运行时错误
- C++析构函数运行时错误:无法munmap
- 如何在 MEX 函数运行时制作它 printf?