插入2D Char数组后在C中打印错误的结果

时间:2018-12-03 00:44:08

标签: c sorting multidimensional-array printf insertion-sort

int const size = 100;
float grades[size];
char students[size][size];
char temp_students[size][size];

int main() {

    int length = 0;
    int i = 0;
    float g = 0;

    printf("How many students do you want to enter? \n ");
    scanf("%d", &length);

    while((i < length)){

        printf("Enter the name and grade \n");
//        scanf("%s", students[i]);
        char temp;
        scanf("%c",&temp); // temp statement to clear buffer
        scanf("%[^\n]", students[i]);
        strcpy(temp_students[i], students[i]);

        printf("Enter the grade again \n");
        scanf(" %f", &g);
        grades[i] = g;

        insertion_sort_float(grades, g, length);
        insertion_sort_string(students, students[i], length);

        i++;
    }
    i--;

    print_report(grades, students, length);

}

void print_report(float grades[], char students[size][size], int number){

   printf("Students Test Report \n");

   printf("Students that took the test: %d \n", number);

    for (int i = 0; i < number; i++){
        for(int j = 0; j < number; j++){
            printf("%c", students[i][j]);
        }
        printf("\n");
    }

    double average = average_number(grades, number);
    double median = median_number(grades, number);
    double highest = max_number(grades, number);
    double lowest = min_number(grades, number);

    printf("Average: %f \n Median: %f \n Highest: %f \n Lowest: %f \n", average, median, highest, lowest);


 }

void insertion_sort_string(char students[size][size], char string[], int array_size) {
    if (array_size+ 1 < size) {// only do insert when there is free space in array
        if (array_size == 0)//empty array, insert at the top directly
            strcpy(students[0], string);

        int insert_index;//to identify the location
        for (int i = 0; i < array_size + 1; i++) {
            insert_index = i;
            if (strcmp(students[i], string)) // due the sorted property of array,
                break;// where the first bigger item showes up, where we should insert    

        }//end of the first for loop
        // if we don't find any bigger item, inset_index will equal to element_num, which means we insert at the tail

        for (int j = array_size; j > insert_index; j--) {
            strcpy(students[j], students[j-1]);

        }// end of the second loop
        strcpy(students[insert_index], string); // do the insert    
    } else {
        printf("overflow!");
        return;
    }
}

这是运行代码时发生的情况:

Output

编写一个程序,允许用户输入参加考试的学生的姓名以及他们获得的成绩。

我不确定为什么没有其他名称被存储。仅打印Gerar。另外,整个字符串都应该打印出来:“ Gerard 78.5”,但这也没有发生。

出于发布目的,省略了某些代码。但是其中包含重要的代码

0 个答案:

没有答案