gpt4 book ai didi

c - for循环函数进入时崩溃

转载 作者:行者123 更新时间:2023-11-30 19:32:20 24 4
gpt4 key购买 nike

我必须输入学生人数,然后输入他们的姓名,然后输入分数。但是当我输入标记时,程序崩溃了。我不知道为什么当我进入最后一个循环函数时它会使我的程序崩溃。也许是因为我嵌套太多?

    #include <stdio.h>
#include <string.h>
#define NAME_LEN 25

int noOfStud(void);
void listStudents(int noOfStud, char names[][NAME_LEN]);
void options(int noOfStud, double marks[]);
void switchOptions(int noOfStud, double marks[]);
void courseWork1(int noOfStud, double marks[]);
void emptyBuffer(void);
int main(void)
{
int students;
char names[students][NAME_LEN];
double marks[students];
students = noOfStud();

listStudents(students, names);
options(students, marks);


return 0;
}

int noOfStud(void)
{
int students;
printf("Number of students: ");
scanf("%d", &students);
getchar();
return students;
}

void listStudents(int noOfStud, char names[][NAME_LEN])
{
int i;
for(i=0; i<noOfStud; i++)
{
printf("Enter name: ");
scanf("%[^\n]", names[i]);
getchar();
}
}

void options(int noOfStud, double marks[])
{
printf("1. Enter marks for course work 1\n");
printf("2. Enter marks for course work 2\n");
printf("3. Enter makrs for course work 3\n");
printf("4. Display a particular student's marks\n");
printf("5. Supervisor mode\n");
printf("6. Exi program\n");

switchOptions(noOfStud, marks);
}

void switchOptions(int noOfStud, double marks[])
{
char options;

printf("\nPlease enter a number for which choice you want: ");
scanf("%d", &options);
emptyBuffer();
switch(options)
{
case 1:
printf("Thank you for chosing to enter marks for course work 1!\n");
courseWork1(noOfStud,marks);
break;
case 2:
printf("Thank you for chosing to enter marks for course work 2!\n");
break;
case 3:
printf("Thank you for chosing to enter marks for course work 3!\n");
break;
case 4:
printf("work 4");
break;
case 5:
printf("work 5");
break;
case 6:
printf("work 6");
break;
default:
printf("You didn't enter anything");
}
}

void courseWork1(int noOfStud, double marks[])
{
int i;
for(i=0; i<noOfStud; i++)
{
printf("Enter marks: ");
scanf("%d", &marks[i]);
getchar();
}

}

void emptyBuffer(void) /* Empty the keyboard buffer */
{
while(getchar() != '\n')
{
;
}

}

一切正常,直到我进入最后一个循环函数,它崩溃了。你们有什么想法吗?谢谢你试图帮助我。

 void courseWork1(int noOfStud, double marks[])
{
int i;
for(i=0; i<noOfStud; i++)
{
printf("Enter marks: ");
scanf("%d", &marks[i]);
getchar();
}

}

最佳答案

您应该使用 %lf 说明符进行双重输入。

scanf("%lf",&marks[i]);

还有 scanf("%c",&options); 因为 options 是 char 类型。

使用错误格式说明符会导致未定义的行为。

在主函数中,您使用一些未初始化的变量初始化数组。

您应该按正确的顺序放置它。

int main(void)
{
int students;

students = noOfStud();
char names[students][NAME_LEN];
double marks[students];
listStudents(students, names);
options(students, marks);


return 0;
}

关于c - for循环函数进入时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47228076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com