gpt4 book ai didi

c - 在链表中动态存储数据的问题

转载 作者:行者123 更新时间:2023-12-02 15:52:54 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,最多读取 8 个银行帐户信息并将它们动态存储在链表中。我编写了一个函数来计算所有输入的银行账户余额的平均值,但是当我尝试调用该函数时,没有产生任何输出。你能帮我找出问题出在哪里吗?

#include <stdio.h>

#include <stdlib.h>

//node structure
typedef struct node {
int no;
char name[20];
float total;
struct node * nextptr;
}
account;

//int for division of total to find the average
static int t;

//adding accounts function
account * addaccount(account * temp) {
fflush(stdin);
printf("Enter the account name: \n");
gets(temp -> name);
printf("Enter the account number: \n");
scanf("%d", & temp -> no);
printf("Enter the account balance: \n");
scanf("%f", & temp -> total);
t++; // used for finding the average
return temp;
}

// function for calculating the average
float sum(account * temp) {
float average = 1.0, sum = 0.0;
int i;
account * start;
temp = start;
for (i = 0; i < t; i++) {
sum += temp -> total;
temp = temp -> nextptr;
}
average = sum / t;
return average;
}

int main() {
int selection;
account * start = NULL;
account * save, * temp;
account * ptr;
ptr = (account * ) malloc(sizeof(account) * 8);
do {
//Menu
printf("\n1.Adding account\n");
printf("2.Find the average of the added accounts' balances\n");
printf("3.Exit\n");
scanf("%d", & selection);
switch (selection) {
case 1: {
if (ptr == NULL)
ptr = (account * ) realloc(ptr, sizeof(account));
save = addaccount(ptr);
if (start == NULL) {
start = save;
start -> nextptr = NULL;
} else {
temp = start;
while (temp -> nextptr != NULL)
temp = temp -> nextptr;
temp -> nextptr = save;
save -> nextptr = NULL;
}
break;
}
case 2: {
float avg;
avg = sum(temp);
printf("%f", avg);
break;
}
case 3: {
temp = start;
while (temp != NULL) {
free(temp);
temp = temp -> nextptr;
}
break;
}
}
} while (selection != 4);
return 0;
}

最佳答案

看这里

// function for calculating the average
float sum(account* temp) {
float average = 1.0, sum = 0.0;
int i;
account* start; <<<==== a random value
temp = start; <<<=== over write the parameter of this function with a random value
for (i = 0; i < t; i++) {
sum += temp->total;
temp = temp->nextptr;
}
average = sum / t;
return average;
}

不确定您在这里要做什么 - 但那肯定是错误的

关于c - 在链表中动态存储数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72051493/

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