[C++] Tạo mảng số thực random giá trị phần tử.
04:36
Lang thang trên mạng gặp bài này làm thử. :))
Đề:Tạo 1 mảng số thực có n phần tử. Các phần tử được tạo ra ngẫu nhiên sao cho phần tử đứng sau lớn hơn phần tử đứng trước.
#include<iostream>
#include <stdlib.h> /* srand, rand */
using namespace std;
float Rand(float a, float b)
{
return a + (b - a)*rand()/RAND_MAX;
};
main () {
int n;
cout<<"How many numbers in the array?";
cin>>n;
float *a= new float[n];
a[1]=Rand(1.0,2.0);
for (int i=2;i<=n;i++){
a[i]=Rand(a[i-1],2.0);
};
for (int i=1;i<=n;i++){
cout<<a[i]<<endl;
};
delete a;
};
Đề:Tạo 1 mảng số thực có n phần tử. Các phần tử được tạo ra ngẫu nhiên sao cho phần tử đứng sau lớn hơn phần tử đứng trước.
#include<iostream>
#include <stdlib.h> /* srand, rand */
using namespace std;
float Rand(float a, float b)
{
return a + (b - a)*rand()/RAND_MAX;
};
main () {
int n;
cout<<"How many numbers in the array?";
cin>>n;
float *a= new float[n];
a[1]=Rand(1.0,2.0);
for (int i=2;i<=n;i++){
a[i]=Rand(a[i-1],2.0);
};
for (int i=1;i<=n;i++){
cout<<a[i]<<endl;
};
delete a;
};