我现在面临一个问题,似乎无法解决它。每当我启动代码时,我都会遇到分段错误。我的目标是掷两个骰子。该值由随机数生成。我想滚动10000次并将值保存在一个数组中,所以我可以在最后创建一个小图表,显示值。我感谢任何有关如何解决问题的帮助和提示。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DICE 2
#define DICEEYES (DICE * 6) -DICE +1
#define COUNT 10000
int diceRoll(int dice);
int main(void)
{
srand(time(0));
int valuesOfRoll[DICEEYES] = { 0 };
for(int i = 0; i < COUNT; i++)
{
int index = diceRoll(DICE) - DICE;
valuesOfRoll[index]++;
}
for(int i = 0; i < DICEEYES; i++)
{
if(valuesOfRoll[i] < 1) continue;
printf("The number %2d was rolled %4d times\r\n", i + DICE, valuesOfRoll[i]);
}
return 0;
}
int diceRoll(int dice)
{
int sum;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
答案 0 :(得分:4)
您应该在函数diceRoll(),
中初始化sum/* always return value between [dice..dice*6]*/
int diceRoll(int dice)
{
int sum=0;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
由于sum可以具有任何值(在堆栈上),因此您使用的索引值可能超出ValuesOfRoll []数组。要避免的一种方法是使用模数运算符将返回的索引限制为有效范围。
int main(void)
{
srand(time(0));
int valuesOfRoll[DICEEYES] = { 0 };
for(int i = 0; i < COUNT; i++)
{
int index = diceRoll(DICE) - DICE;
/* limit index to [0..DICEEYES] */
index %= DICEEYES;
valuesOfRoll[index]++;
}
for(int i = 0; i < DICEEYES; i++)
{
if(valuesOfRoll[i] < 1) continue;
printf("The number %d was rolled %4d times", i + DICE, valuesOfRoll[i]);
}
return 0;
}
答案 1 :(得分:1)
初始化函数中sum
的值(最好为0),否则它将保留一些垃圾值。
int diceRoll(int dice)
{
int sum;
for(int i = 0; i < dice; i++)
{
sum += rand() % 6 + 1;
}
return sum;
}
垃圾值可能是一个非常大的数字,因此函数的返回值也是如此。因此,当在此行中使用返回值时:
int index = diceRoll(DICE) - DICE;
然后数组将有一个大数字的索引valuesOfRoll[some_large_integer]++;
。这会导致数组外的情况,并导致seg-fault。
答案 2 :(得分:1)
稍微迟了一点,故障没有初始化sum
和DICEEYES
。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DICE 2
#define DICEEYES (DICE * 6)
#define COUNT 10000
int diceRoll(int dice)
{
int i, sum = 0; // need to initialise!
for(i = 0; i < dice; i++)
sum += rand() % 6 + 1;
return sum;
}
int main(void)
{
int i;
int valuesOfRoll[DICEEYS+1] = { 0 }; // size of array
srand((unsigned)time(0));
for(i = 0; i < COUNT; i++)
valuesOfRoll[diceRoll(DICE)]++;
for(i = DICE; i <= DICEEYES; i++)
printf("The number %2d was rolled %4d times\n", i, valuesOfRoll[i]);
return 0;
}
节目输出:
The number 2 was rolled 264 times
The number 3 was rolled 573 times
The number 4 was rolled 798 times
The number 5 was rolled 1145 times
The number 6 was rolled 1373 times
The number 7 was rolled 1697 times
The number 8 was rolled 1385 times
The number 9 was rolled 1143 times
The number 10 was rolled 835 times
The number 11 was rolled 528 times
The number 12 was rolled 259 times
答案 3 :(得分:0)
以下代码
Get-ADComputer -Filter * | ? { $members -notcontains $_.Name }