gpt4 book ai didi

c - 简单的 C 数组结构

转载 作者:行者123 更新时间:2023-12-04 06:10:48 26 4
gpt4 key购买 nike

我一直试图从解释结构数组的教科书中调整这个问题。
我的输出是正确的,但是当我在结构中添加另一个“人”并尝试打印结果(在 displayStats() 中的第二个打印语句中)时,它输出 4 行而不是 2 行。运行此代码,输出为:

Hoover, Adam: 10.400000 PPG in 2005, : 0.000000 PPG in 0.N=ö, Ðè/: 0.000000 PPG in 1Jane, Mary: 10.400000 PPG in 2005


这有点有趣,因为即使我注释掉第二个打印语句(打印 Mary Jane 行),输出仍然是 2 行——胡佛,亚当是第 1 行,而 : 0.00000 是第 2 行。当我做数组 [32] 中的所有 4 个字段,我仍然得到 4 行输出,但中间的 2 行更改了一点。

我可能遗漏了一些非常简单的东西,但目标只是让 Hoover、Adam 和 Jane、Mary 输出 2 行。
#include <stdio.h>
#include <string.h>


struct person { /* "person" is name for structure type */
char first[32]; /* first field of structure is array of char */
char last[32]; /* second field is array of char */
int year; /* third field is int */
double ppg; /* fourth field is double */

char second[31];
char third[31];
int year1;
double ppo;
}; /* ending ; means end of structure type definition */


displayStats(struct person Input) {
printf("%s, %s: %lf PPG in %d\n", Input.last, Input.first, Input.ppg, Input.year);
printf("%s, %s: %lf PPG in %d\n", Input.third, Input.second, Input.ppo, Input.year1);
}

int main(int argc,char *argv[]) {
struct person teacher;
struct person another;

teacher.year=2005;
teacher.ppg=10.4;
strcpy(teacher.first,"Adam");
strcpy(teacher.last,"Hoover");
displayStats(teacher);

another.year1=2005;
another.ppo=10.4;
strcpy(another.second,"Mary");
strcpy(another.third,"Jane");
displayStats(another);

return (0);
}

最佳答案

你看到垃圾是因为老师,secondthird没有分配,另一个,firstlast没有分配?

你为什么有 secondthird领域?删除它们,使用 firstlast对于两者,并删除 displayStats 中的第二行,它应该可以工作。

关于c - 简单的 C 数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812994/

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