C 函数编程

C programming with functions

我的代码还有一些问题。该程序要求用户指定投掷次数,然后投掷 3 个骰子并将这 3 个骰子相加求和。

然后另一个函数使用冒泡排序算法从最小到最大对总和进行排序。

前两个函数似乎可以工作,但程序没有打印出第三个排序函数的结果。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 100

//This function ask the user for the amout of throws
int numberofthrows() {
    int throws
    printf("Type in the number of throws");
    scanf("%d", &throws);
    return throws;
}

//This function makes the random throws of 3 dices with regard to the number of throws    

int filler(int thrownr, int dice1[MAX], int dice2[MAX], int dice3[MAX], int    sum[MAX]) {
    int i, nr;
    srand(time(NULL));
    for(i = 0; i <= thrownr; i++) {
        nr = rand()%6;
        dice1[i] = nr + 1;
        nr = rand()%6;
        dice2[i] = nr + 1;
        nr = rand()%6;
        dice3[i] = nr + 1;
        sum[i] = dice1[i] + dice2[i] + dice3[i];
    }

    int j;
    for(j = 0; j <= thrownr; j++) {
        printf("%d ", dice1[j]);
        printf("%d ", dice2[j]);
        printf("%d ", dice3[j]);
        printf("%d\n", sum[j]);
    }
}

//This function sorts the result in form the sum array

int sorter(int thrownr, int sum[MAX], int sortsum[MAX]) {
    int tmp, i, j, k, m;
    for(i = 0; i <= thrownr; i++) {
        sortsum[i] = sum[i];
    }
    for(m = 0; m <= 10; m++) {
        for(j = 0; j <= thrownr; i++) {
            if (sortsum[j] > sortsum[j+1]) {
                tmp = sortsum[j];
                sortsum[j] = sortsum[j+1];
                sortsum[j+1] = tmp;
            }
        }
    }

    for(k = 0; k <= thrownr; k++) {
        printf("%d\n", sortsum[k]);
        printf("%d\n", sum[k]);
    }
}
int main(void) {
    srand(time(NULL));
    int dice1[MAX];
    int dice2[MAX];
    int dice3[MAX];
    int sum[MAX];
    int sortsum[MAX];
    int numberofthrows2;
    numberofthrows2 = numberofthrows();
    filler(numberofthrows2, dice1, dice2, dice3, sum);
    sorter(numberofthrows2, sum, sortsum);
    return 0;
}

排序代码有点错误。变化

for(m = 0; m <= 10; m++)

for(m = 0; m <= thrownr-1; m++)

for(j = 0; j <= thrownr; i++)

for(j = 0; j < thrownr-m-1; i++)

修复它。此外,在 main 的开头调用 srand 一次 。不要在程序中多次调用它,否则每次 运行 您的程序都可能得到相同的 "random" 数字。