Categories: C/C++ | Tags: | Views: 2,231
 
模拟一个”21 减”的游戏。这个游戏在开始时的上限值为21,并且经过很多回合。在一个回合中抓阄,所抓的每个阄上可以写任何一个正数,并且把这些值相加,直到您最少有16点。从这个点数您可以结束一个回合。
如果点数大于当前的上限值,您就输掉了当前的回合。点数正好符合上线数,则对于下一个回合而言,其上限减少1,否则存在不分胜负。一旦上限值变为19,则游戏被中断。
 
必要条件:
 
写一个子程序 int loseZiehen(int obergrenze) – 使用的输入控制子程序中的变量 obergrenze(上限值),并且返回抓过的阄上的数字的总和。在主程序中,一个新回合被开始,或者上限值被降低。
 
程序运行举例:
 
上限值是 21
到现在0 点 新抓得的数? 19
到现在19 点 还要抓一次 (JA = 1 / NO = 0)? 1
到现在19 点 新抓得得值?1
到现在20 点 还要抓一次 (JA = 1 / NO = 0)? 0
 
不分胜负 – 上限值是 21
到现在0 点 新抓得的数? 22
 
输了 – 上限值是 21
到现在0 点 新抓得的数? 12
到现在12 点 新抓得得值?9
 
赢了 -上限值是 20
到现在0 点 新抓得的数? 20
 
赢了 -上限值是 19
游戏结束!
代码:
 
#include <stdio.h>
 
int loseZiehen(int obergrenze){
 
    int point = 0;  //现在的点数 
    int again = 1;  //再抓一次?
    do {
 
        if( point < 16 || (point >= 16 && again) ){
            int r = rand()%30 + 1;  // % 防止产生的随机数太大 
            printf("到现在 %d 点 - 新抓到的数? %d\n",point,r);
            point += r;
        } 
        if( point >= 16 && point < obergrenze ){
            printf("到现在 %d 点 - 还要抓一次(JA=1/NO=0)? ",point);
            scanf("%d", &again);
        }
 
    } while( again && point < obergrenze ); 
    return point; 
}
 
int main(){
    srand(time(NULL));
    int obergrenze = 21;
    int points = 0; 
    printf("上限值是 21\n");
 
    do{
        points = loseZiehen(obergrenze);//一轮的点数 
        printf("\n");
        if(points == obergrenze){
            obergrenze --;
            printf("赢了 - "); 
        } else {
            printf("%s - ", points>obergrenze?"输了":"不分胜负" )    ; 
        }
        printf("上限值是 %d\n", obergrenze);
 
 
    }while(obergrenze!=19);
 
    printf("游戏结束!\n"); 
 
    system("pause");
}

RELATED POSTS:

  1. 常用的C++字符串操作函数
  2. Jacobi法求特征值和特征向量[C++]
  3. 一个扩展的C++数组的类
  4. 国外的C语言考题-自动售货机
  5. 国外的C语言考题-二项式系数
  6. 国外的C语言考题-滚梯
No comments yet.
;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)

你可以使用@somebody:开头, 来邮件通知somebody你回复了他的留言(用户名区分大小写).