简单C语言—随机数的产生
admin 于 2012年11月03日 发表在 C/C++开发笔记

下面程序是模拟投掷骰子的程序,输入投掷的总次数,会显示从1-6不同的点数出现的不同次数,而且数字全为随机的,什么意思呢?就是说:你每次输入即使是相同的投掷次数,显示1-6出现的次数都可能是不相同,其实就是电玩游戏的一个缩影

源码:点击下载附件

 /* Fig. 5.8: fig_08.c */
 #include <stdio.h>
 #include <stdlib.h>
 
 /* function main begins */
 int main( void )
 {
     int frequency1 = 0;
     int frequency2 = 0;
     int frequency3 = 0;
     int frequency4 = 0;
      int frequency5 = 0;
     int frequency6 = 0;
 
     int i;
     int roll; /* roll counter, value 1 to i */
     int face;
     printf( "Input the i's number: " );
     scanf( "%d", &i );
     srand( time( NULL ) ); /* *************************** */
 
     /* loop i times and output results */
     for ( roll = 1; roll <= i; roll++ ){
             face = 1 + rand() % 6;
 
         switch ( face ){
         case 1:
         ++frequency1;
         break;
 
         case 2:
         ++frequency2;
         break;
 
         case 3:
         ++frequency3;
         break;
 
         case 4:
         ++frequency4;
         break;
 
         case 5:
         ++frequency5;
         break;
 
         case 6:
         ++frequency6;
         break;
         }  /*end swith*/
     }
     /* display the results */
     printf( "%s%13s\n", "face", "Frequency" );
     printf( " 1%13d\n", frequency1 );
     printf( " 2%13d\n", frequency2 );
     printf( " 3%13d\n", frequency3 );
     printf( " 4%13d\n", frequency4 );
     printf( " 5%13d\n", frequency5 );
     printf( " 6%13d\n", frequency6 );
     return 0;  /* successful terminnation */
 }  /* end main */

注意:本站所有文章除特别说明外,均为原创,转载请务必以超链接方式并注明作者出处。 标签:C/C++