使用for循环和rand生成100个随机数并打印出最小和最大的数字。如果我正朝着正确的方向前进,那么任何指导。
int main()
{
int x = rand();
for( x = 0; x < 100; x++)
{
if( x < x )
{
cout << "Small numbers: " << endl;
cout << x << endl;
}
if ( x > x )
{
cout << "Big numbers: " << endl;
cout << x << endl;
}
}
system("pause");
}
答案 0 :(得分:3)
if( x < x )
和
if (x > x)
永远不会成真。你的逻辑不对。
您可以执行以下操作:
int main()
{
//set up seed
srand(time(NULL));
double min = 1000; //you can also use numeric limits
double max = -1000;
for (int i = 0; i < 100; ++i)
{
double r = rand(); //you can also generate rand in given range
if (r > max)
{
max = r;
}
if (r < min)
{
min = r;
}
}
cout << min << " " << max <<endl;
cin.get(); //don't use system pause
}
答案 1 :(得分:1)
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int smallest = INT_MAX;
int largest = 0;
for( int x = 0; x < 100; x++)
{
int randomNumber = rand() % 100 + 1;
cout << "Next number: " << randomNumber ;
if( randomNumber > largest )
{
largest = randomNumber ;
}
if ( randomNumber < smallest )
{
smallest = randomNumber ;
}
}
cout << "Smallest number: " << smallest;
cout << "Largest number:"<< largest;
system("pause");
}
答案 2 :(得分:1)
首先,你必须在每次越过循环时生成新的随机int,所以你想要这样的东西:
#include <iostream>
#include <cstdlib>
#include <limits>
using namespace std;
int main()
{
int x = rand();
int min=RAND_MAX;
int max=0;
for( int i = 0; i < 100; i++)
{
x = rand();
if( x < min )
{
cout << "Small numbers: " << endl;
cout << x << endl;
min=x;
}
if ( x > max )
{
cout << "Big numbers: " << endl;
cout << x << endl;
max=x;
}
}
system("pause");
}
答案 3 :(得分:0)