问题描述

编制100以内两个整数(随机产生)的加法运算练习程序。

分析

变量

四个整型变量:分别表示两个加数、两个和(计算机和人算结果)
一个布尔变量(或整型也可):表示运算结果是否正确
整型:表示题目总数量,答对题目数

库和函数

C语言

printf() 输出函数
scanf()输入函数
rand()在“stdlib.h”中。每调用一次rand()函数,可以产生一个0-32767之间的随机数(2-2).一般情况下,要想得到[a,b]区间的随机数,可以使用表达式a+rand()%(b-a)
srand() 随机数种子,种子不同产生的随机数不同

python

random()库
1)random() :用来产生[0.0,1.0)之间的随机数
(2)seed(a=None):初始化随机数种子
(3)randint(a,b):随机产生一个[a , b]的整数
time库
(1)time():获取当前时间

源程序

C语言

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int main()
  4. {
  5. int a,b,c1,c2,socres=0,num=0;
  6. while(1)
  7. {
  8. a = rand()%100; //随机生成第一个加数
  9. b = rand()%100; //随机生成第二个加数
  10. c1 = a + b; //正确的和
  11. num += 1; //题号
  12. //printf("num:%d",num);
  13. printf("%d. %d加%d等于?",num,a,b);
  14. scanf("%d",&c2); //用户输入的计算结果
  15. if(c2 == c1)
  16. {
  17. printf("你真棒,答对了!\n ");
  18. socres++;
  19. }
  20. else
  21. printf("哎呀,你答错了呢。正确答案是%d\n",c1);
  22. printf("截止目前,您一共回答了%d道题目,答对了%d道题目,正确率为%.2f%%\n",num,socres,(float)socres/num*100);
  23. }
  24. return 0;
  25. }

运行发现每次程序运行产生的随机数都是固定的,属于“伪随机随”。需要利用time.h引入一个种子,以保证每次播种产生的随机数是不同的。

http://c.biancheng.net/view/2043.html

完善后的代码为:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    int a,b,c1,c2,socres=0,num=0;
    while(1)
    {
    srand((unsigned)time(NULL));   //随机数种子
    a = rand()%100;  //随机生成第一个加数
    b = rand()%100;  //随机生成第二个加数
    c1 = a + b;      //正确的和
    num += 1;        //题号
    //printf("num:%d",num);
    printf("%d. %d加%d等于?",num,a,b);
    scanf("%d",&c2);   //用户输入的计算结果
    if(c2 == c1)
    {
        printf("你真棒,答对了!\n ");
        socres++;
    }
    else
        printf("哎呀,你答错了呢。正确答案是%d\n",c1);

    printf("截止目前,您一共回答了%d道题目,答对了%d道题目,正确率为%.2f%%\n",num,socres,(float)socres/num*100);
    }
    return 0;
}

python

#coding:gbk
import random
import time

num,socres = 0,0
while True:
    random.seed(time.time())   #利用时间生成当前时间的随机数种子
    num += 1
    a = random.randint(0,99)   #第一个加数
    b = random.randint(0,99)   #第二个加数
    c1 = a + b                 #正确的和
    c2 = int(input("{}. {} + {} = ? ".format(num,a,b)))   #格式化输入,用户的计算结果
    if c2 == c1:
        print("你真棒,答对了!")
        socres += 1
    else:
        print("哎呀,你答错了呢。正确答案是"+str(c1))
    print("截止目前,你一共回答了"+str(num)+"道题目,答对了"+str(socres)+"道题目,正确率为"+str(round(float(socres/num*100),2))+"%")
    #print("截止目前,您一共回答了{}道题目,答对了{}道题目,正确率为{}%".format(num,socres,round(float(socres/num*100),2)))   #作用和上一行一样