gpt4 book ai didi

c - 无法正确启动 int 并从函数中保留数字

转载 作者:行者123 更新时间:2023-11-30 17:30:00 25 4
gpt4 key购买 nike

首先对我的英语感到抱歉,我会尽力而为。

好吧,问题来了,我正在制作一个C程序只是为了学习,该程序基本上是一个学生管理器,我想添加一个最终功能,其中用户将通过删除和插入后提示用户该学生的 id 将从数据库中删除,问题是...当在第一种情况下插入数据时,添加了一个子例程,该子例程自动将 id 添加为结构体中的 int ,问题是它显示一个随机 int 数字像“43405”左右我想将整数开始为1,问题是当再次调用该函数时id将恢复为1,而这根本不起作用。

P.D:我读到你们中的一些人告诉我要让代码更具可读性,你能给我一个很好的“教程”吗?

功能:

int insertar_notas(struct alumnos notas[20], int n,int id_alumno){


char resp[3];

system("cls");
puts("\n \a Insercion del alumno\n");
while (!strstr(resp,"no")){
fflush(stdin);
printf("\nEl ID de este alumno sera: %d\n", id_alumno);
notas[n].id=id_alumno;
id_alumno++;
puts("\nDime el nombre del Alumno\n");
scanf("%10s", notas[n].alumno );
system("cls");
fflush(stdin);
puts("\nDime el apellido del Alumno\n");
scanf("%10s", notas[n].apellido );
system("cls");
puts("\nDime la Primera nota trimestral del Alumno[1.23]\n");
scanf("%f", &notas[n].nota1 );
system("cls");
puts("\nDime la Segunda nota trimestral del Alumno[1.23]\n");
scanf("%f", &notas[n].nota2 );
system("cls");
puts("\nDime la Tercera nota trimestral del Alumno[1.23]\n");
scanf("%f", &notas[n].nota3 );
n++;
system("cls");
puts("\nQuieres volver a insertar otro?[si|no]\n");
scanf("%3s", resp);
strlwr(resp);

}

return n;

return id_alumno;




}

主要了解更多信息:

int main (void){

int menu = 0, n = 0, id_alumno;
struct alumnos notas[20];


puts("\n<><><>Bienvenido al recuento de notas de la escuela<><><>\n");
puts("\nQue deseas hacer?\n");


while (menu != 5){

puts("\n1)Insertas las notas de un alumno\n2)Ver todas las notas\n3)Ver las notas de un alumno\n4)Modificar notas\n5)Salir\n");
scanf("%d", &menu);
switch(menu){

case 1:

n=insertar_notas(notas,n,id_alumno);
break;

最佳答案

C 使用按值传递,因此要使 id_alumno 可修改,您需要将其作为指针传递:

int insertar_notas(struct alumnos notas[20], int n,int *id_alumno) { // id_alumno is now a pointer to int inside this function


char resp[3];

system("cls");
puts("\n \a Insercion del alumno\n");
while (!strstr(resp,"no")){
fflush(stdin);
printf("\nEl ID de este alumno sera: %d\n", *id_alumno); // Use * to access the value
notas[n].id=id_alumno;
(*id_alumno)++; // Use * to access the value. ++ has higher precedence than *, so need parenthesis around *id_alumno
...

在 main 的调用中:

                    n=insertar_notas(notas, n, &id_alumno);  // address-of id_alumno

此外,您需要在main中初始化id_alumno:

int menu = 0, n = 0, id_alumno = 1;    

关于c - 无法正确启动 int 并从函数中保留数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25359221/

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