【发布时间】:2015-10-28 03:46:35
【问题描述】:
对于一个作业,我正在编写代码来计算计算 2 个掷骰子的总和的次数...例如,如果 die 1 是 5,die 2 是 6,那么 timesRolled[(die 1 + die 2)] 将递增。代码如下,它演示了我的逻辑。返回的值是垃圾,我需要帮助确定我在哪里出错了。提前致谢!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
int main() {
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
int timesRolled[] = { 0 };
int pointerVal = 0;
int rollNumber = 0;
int die1 = 0; // Dice values
int die2 = 0; // Dice values
int rollTotal = 0; // Sum of dice values
printf("Enter number of rolls: ");
scanf_s("%d", &numRolls);
srand(time(0));
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = rand() % 6 + 1;
die2 = rand() % 6 + 1;
rollTotal = die1 + die2;
++timesRolled[(rollTotal)];
printf("\nRoll %d is %d (%d+%d)",(i + 1), rollTotal, die1, die2);
}
printf("\n\nDice roll statistics: \n");
for (pointerVal = 1; pointerVal <= 12; ++pointerVal) {
printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);
}
}
else {
printf("Invalid rolls. Try again.\n");
}
_getch();
return 0;
}
【问题讨论】: