我有一個任務要求我做一個生成亂數學問題的測驗。我對一切都很好,但我正在努力尋找一種在數學運算子“ ”和“-”之間隨機選擇的方法。
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
int choice = 0;
int lives = 0;
int question = 1;
int a;
int b;
int answer = 0;
int ans = 0;
int correct = 0;
printf("\n Welcome to Maths Tester Pro.");
printf("\n Please Select a difficulty:");
printf("\n 1) Easy");
printf("\n 2) Medium");
printf("\n 3) Hard \n");
scanf("%d%*c",&choice);
switch(choice)
{
case 1:
printf("You have selected Easy mode!");
lives = lives 3;
while ((lives !=0)&&(question !=6)){
if(question !=5){
//Ask Question
printf("\nQuestion %d of 5. You have %d lives remaining", question, lives);
srand(time(NULL));
a = (rand() % (10 - 1 1)) 1; //make the sign random
b = (rand() % (10 - 1 1)) 1;
printf("\n%d %d = ",a ,b);
scanf("%d", &answer);
ans = a b;
//If answer is correct
if((a b) == answer){
printf("Correct!\n");
correct = correct 1;
}
//If answer is incorrect
else{
printf("Incorrect! The correct answer was %d\n",ans);
lives=lives-1;
}
question = question 1;
}
在我的代碼中,我將它寫為 ans=a b 但我希望它能夠隨機選擇“ ”或“-”。
uj5u.com熱心網友回復:
最簡單的方法是更改?? 的符號b。為此,只需將其乘以1(保持正號)或-1(使其變為負號):
b = b * ((rand() - (RAND_MAX / 2)) > 0 ? 1 : -1);
執行后,您將隨機獲得a b或a (-b)。
結果運算子的示例列印:
printf("%d%s%d = %d\n", a, (b > 0 ? " " : ""), b, a b);
注意:正如前面評論中所指出的,您可能還希望隨機化種子,以防止您的應用程式繼續提供“相同”的亂數:
/* Randomize seed (needed once). */
srand(time(NULL));
/* Then make your calls to `rand()`. */
...
uj5u.com熱心網友回復:
我提供這個作為如何干凈地生成和列印您似乎想要的問題的示例。
這會產生 20 個“和”和/或“差”方程。您可以簡單地禁止列印總數,以便向用戶提出問題。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand( time( NULL ) );
for( int i = 0; i < 20; i ) {
int a = (rand() % 10) 1; // 1 <= a <= 10
int b = (rand() % 20) - 9; // -9 <= b <= 10
printf( "%d %c %d = %d\n", a, " -"[b<0], abs( b ), a b );
}
return 0;
}
1 3 = 4
1 - 6 = -5
4 10 = 14
8 2 = 10
10 0 = 10
4 4 = 8
8 10 = 18
8 9 = 17
8 - 2 = 6
8 - 4 = 4
2 1 = 3
8 - 5 = 3
2 - 6 = -4
4 9 = 13
6 6 = 12
5 0 = 5
3 4 = 7
1 0 = 1
9 - 5 = 4
8 8 = 16
敏銳的讀者會注意到,即使是“10 0”也是一個合理的問題。零是用于加法的恒等運算子(?)(如 1 是用于乘法的恒等運算子(?)。)
您可以自由調整術語的范圍以適應您的問題。
uj5u.com熱心網友回復:
您可以使用標準庫中定義的 rand() 函式。而如果你想讓你的程式每次運行時給你不同的亂數,你需要把 srand(time(NULL)) 放在開頭,但是對于時間函式,你需要包含 time.h 庫
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/511534.html
標籤:C数学随机的
上一篇:如何找到滿足多個條件的最小值
