你好,怎样用c语言输出一个1到100的随机数

如题所述

源程序如下:

#include "pch.h"

#include <iostream>

#include <time.h>

using namespace std;

int main()

{

 const int n = 10000;

 int number[n] = { NULL };

 srand((unsigned)time(NULL));

 number[0] = rand() % n;      //第一个随机数无需比较

 cout << number[0] << " ";

 for (int i = 1; i < n; i++)     //其余随机数循环产生

 {

  int j = 0;

  number[i] = rand() % n;

  while (1)

  {

   if (number[i] == number[j])   //若有相同则继续循环重新安排随机数

   {

    number[i] = rand() % n;

    j = 0;       //若遇到相同的就从头遍历

    continue;

   }

   if (j == (i - 1))      //若遍历完就跳出

    break;

   j++;

  }

  cout << number[i] << " ";

 }

 cout << endl;

 return 0;

}

程序运行结果:


扩展资料:

其他实现方式:

#include<time.h> //使用 time 函数必须引入 time.h 头文件

#include<stdlib.h>

int main()

{

 srand((int)time(0));

 int rand_num = rand();

 printf("rand_num = %d\n", rand_num);

 return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-24
include <stdio.h>
#include<time.h>
#include<stdlib.h>
main()
{
int i;
srand(time(0));
i=rand()%100+1;/*随机函数*/
printf("%d",i);。
第2个回答  2011-12-07
#include <stdio.h>
#include<time.h>
#include<stdlib.h>
main()
{
int i;
srand(time(0));
i=rand()%100+1;/*随机函数*/
printf("%d",i);
}
这个一定可以,望楼主采纳!本回答被提问者采纳
第3个回答  2011-12-07
//两个函数srand()产生随机数种子,rand产生随机数
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
srand( time(NULL) );
printf( "Random number:%d\n", rand()%100 );

return 0;
}
第4个回答  2011-12-07
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
int main(){
srand(time(NULL));
int num;
num=rand();
while(num<1||num>100){
num=rand();
}
printf("%d\n",num);
system("pause");
return 0;
}
相似回答