c語言實現這個簡單的功能
記錄自己在嵌入式這行的學習,希望能夠幫助到努力成長的你。
主要涉及知識點循環分支語句,隨機函數
- 平臺:ubuntu
- 代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int x = 0, y = 0,z = 0, i = 0, num = 0, score = 0;//num玩家錄入值
int Num = 0;//系統計算值
char c = 0;
srand(getpid());
for(i = 0; i < 10; i++)
{
x = rand() % 100;
y = rand() % 100;//x, y 兩個隨機操作數
z = rand() % 5;
//獲得運算符
switch(z)
{
case 0 : c = ‘+’;;break;
case 1 : c = ‘-’;break;
case 2 : c = ‘*’;break;
case 3 : c = ‘/’;break;
case 4 : c = ‘%’;
}
while(c == '/' && y == 0)//除數若爲0,重新生成除數至不爲0
{
y = rand() % 100;
}
//生成題目並錄入回答
printf("%d %c %d = “, x ,c ,y);
scanf(”%d", &num);
//系統計算正確答案Num
if(c == ‘+’)
{
Num = x + y;
}
else if(c == ‘-’)
{
Num = x - y;
}
else if(c == ‘*’)
{
Num = x * y;
}
else if(c == ‘/’)
{
Num = x / y;
}
else
{
Num = x % y;
}
//判斷正確與否,並計算分數
if(Num == num)
{
printf(“回答正確!加10分!\n”);
score += 10;
}
else
{
printf(“很遺憾!回答錯誤!\n”);
printf(“正確答案爲%d\n”, Num);
}
}
printf("\n");
printf(“最終得分爲:%d 分!\n”, score);
return 0;
}
3.結果如下: