gpt4 book ai didi

c - 如何在 C 程序中嵌套函数?

转载 作者:行者123 更新时间:2023-11-30 21:35:45 24 4
gpt4 key购买 nike

有谁知道我如何更改我的代码以包含一个对表的每一行进行平均的函数(而不是在主函数中完成)?每次我尝试使用 process_student 函数运行代码时,它根本不打印表格。我首先包含了我的工作“非功能”代码,然后是包含 process_student 函数的失败代码。提前致谢!

此外,我正在使用重定向输入 .txt 文件!

#include <stdio.h>

int main(void)
{

int month = 0;
int date = 0;
int year = 0;
int x = 0;
int id = 0;
int min_user = 0;
int ms = 0;
int realTest = 0;
float min = 10000000;
float t1 = 0;
float t2 = 0;
float t3 = 0;
float t4 = 0;
float avg_trial = 0;

scanf("%d %d %d", &month, &date, &year);
printf("\nStudy Date: %02d/%02d/%02d\n", month, date, year);

printf("Student Trial-1 Trial-2 Trial-3 Trial-4 Average\n");

while (x < 10) {
realTest = 0;
scanf("%d %f %f %f %f", &id, &t1, &t2, &t3, &t4);
if (t1>0)
realTest += 1;
if (t2>0)
realTest += 1;
if (t3>0)
realTest += 1;
if (t4>0)
realTest += 1;
avg_trial = (t1+t2+t3+t4)/realTest;
if (realTest == 0)
avg_trial = 0.000;
if (id<1000) {
printf(" %d %.3f %.3f %.3f %.3f %.3f\n", id, t1, t2, t3, t4, avg_trial);
x++;
}
else {
printf(" %d %.3f %.3f %.3f %.3f %.3f\n", id, t1, t2, t3, t4, avg_trial);
x++;
}
if (avg_trial < min && avg_trial > 0) {
min = avg_trial;
min_user = id;
}

}

ms = min * 1000;
printf("\nStudent %d had the lowest average of %.3f seconds (%d milliseconds)\n", min_user, min, ms);

return 0;
}

这是我失败的代码,其中包含 process_student 函数: #包括

 int main(void)
{

int month = 0;
int date = 0;
int year = 0;
int x = 0;
int id = 0;
int min_user = 0;
int ms = 0;
float min = 10000000;
float t1 = 0;
float t2 = 0;
float t3 = 0;
float t4 = 0;
float avg_trial = 0;

scanf("%d %d %d", &month, &date, &year);
printf("\nStudy Date: %02d/%02d/%02d\n", month, date, year);

printf("Student Trial-1 Trial-2 Trial-3 Trial-4 Average\n");

ms = process_student(min) * 1000;
printf("\nStudent %d had the lowest average of %.3f seconds (%d milliseconds)\n", min_user, min, ms);

int process_student(void) {
float t1, t2, t3, t4, avg_trial, min;
int min_user;
int realTest = 0;

while (x < 10) {
scanf("%d %f %f %f %f", &id, &t1, &t2, &t3, &t4);
if (t1>0)
realTest += 1;
if (t2>0)
realTest += 1;
if (t3>0)
realTest += 1;
if (t4>0)
realTest += 1;
avg_trial = (t1+t2+t3+t4)/realTest;
if (realTest == 0)
avg_trial = 0.000;
if (id<1000) {
printf(" %d %.3f %.3f %.3f %.3f %.3f\n", id, t1, t2, t3, t4, avg_trial);
x++;
}
else {
printf(" %d %.3f %.3f %.3f %.3f %.3f\n", id, t1, t2, t3, t4, avg_trial);
x++;
}
if (avg_trial < min && avg_trial > 0) {
min = avg_trial;
min_user = id;
}

}

return min;
return min_user;
}

return 0;
}

最佳答案

只需在 main 之前定义嵌套函数,或者在 main 之前或 header 中添加声明,然后在其他地方定义它。您似乎没有理由需要嵌套函数。

嵌套函数不是合法的 ISO C。GNU C 编译器允许将它们作为扩展。但同样,似乎没有理由不将 process_student() 声明和定义为标准函数。

关于c - 如何在 C 程序中嵌套函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456843/

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