gpt4 book ai didi

C程序使用结构体显示识字率最高和收入最高的州

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

当我运行下面的代码来查找最大识字率和最大收入时,程序正确地获取输入,但最后在显示最后两个 printf 语句的输出时,我收到以下错误“段错误。核心已转储”。请解释一下出了什么问题..提前致谢。

#include<stdio.h>
#include<stdlib.h>

#define MAX 50
struct state_det {
char name[50];
long population;
float literacy;
long income;
}s[MAX];

int main()
{
int n,i,max_lit = 0, max_income = 0;
int t, p;
printf("enter number of states\n");
scanf("%d",&n);

for(i = 0; i < n; i++)
{
printf("enter the name of the state %d\n",i);
scanf("%s",&s[i].name);
printf("enter the population of the state %d\n",i);
scanf("%ld",&s[i].population);
printf("enter the literacy rate of the state %d\n",i);
scanf("%f",&s[i].literacy);
printf("enter the average income of the state %d\n",i);
scanf("%ld",&s[i].income);
}

max_lit = s[0].literacy;
max_income = s[0].income;

for(i = 1; i < n; i++)
{
if(max_lit < s[i].literacy) {
max_lit = s[i].literacy;
t = i;
}

if(max_income < s[i].income) {
max_income = s[i].income;
p = i;
}
}

printf("\nthe state with highest literacy is %s and rate = %f\n",s[t].name, s[t].literacy);

printf("\nthe state with highest income is %s and rate = %ld\n",s[p].name, s[p].income);


return 0;
}

最佳答案

线路

scanf("%s",&st[i].name);

应该是

scanf("%s",s[i].name);

因为说明符 %s 正在查找 char* 并且您正尝试传递 char (*)[50]

关于C程序使用结构体显示识字率最高和收入最高的州,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627735/

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