Đăng nhập để hỏi chi tiết


Hãy luôn nhớ cảm ơn và vote 5*
nếu câu trả lời hữu ích nhé!
`***` Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i;
int x1, x2, sum;
int count[13] = {0}; // lưu số lần xuất hiện từ 0 -> 12 (chỉ dùng 2->12)
srand(time(NULL)); // tạo seed ngẫu nhiên
for (i = 0; i < 100; i++) {
x1 = rand() % 6 + 1; // xúc xắc 1
x2 = rand() % 6 + 1; // xúc xắc 2
sum = x1 + x2;
count[sum]++; // tăng số lần xuất hiện
}
// In kết quả
printf("Thong ke sau 100 lan tung:\n");
for (i = 2; i <= 12; i++) {
printf("Tong = %d: %d lan\n", i, count[i]);
}
}
`***` Giải thích
`\text{rand() % 6 + 1}` `->` tạo số từ `1` đến `6` (giống xúc xắc).
`\text{count[sum]++}` `->` đếm số lần xuất hiện của mỗi tổng.
Mảng `\text{count[13]}` dùng để lưu từ `0 -> 12` (nhưng chỉ cần `2 -> 12`).
Hãy giúp mọi người biết câu trả lời này thế nào?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int diceRolls[13] = {0};
int roll1, roll2, sum;
srand(time(0));
for (int i = 0; i < 100; i++) {
roll1 = rand() % 6 + 1;
roll2 = rand() % 6 + 1;
sum = roll1 + roll2;
diceRolls[sum]++;
}
printf("Tổng số lần lăn súc sắc trong 100 lần:\n");
for (int i = 2; i <= 12; i++) {
printf("Điểm %d: %d lần\n", i, diceRolls[i]);
}
return 0;
}
Hãy giúp mọi người biết câu trả lời này thế nào?
Bảng tin