gpt4 book ai didi

c++ - 为什么我的程序不打印字符串?

转载 作者:行者123 更新时间:2023-11-27 23:56:50 26 4
gpt4 key购买 nike

我的程序需要学生的姓名和年龄,这个函数应该找到打印最小的学生的名字、最大的学生的名字和平均年龄。但是它不打印最小的学生的名字谁能告诉我为什么?

void check(string *nameStudent, int *ageStudent, int num) {
int i, young = 0, old = 0, sum = 0, mov = 0;
string a, b;
double average;
for (i = 0; i < num; i++){
if (*(ageStudent + mov) < young) {
young = *(ageStudent + mov);
a = *(nameStudent + mov);
}
if (*(ageStudent + mov) > old) {
old = *(ageStudent + mov);
b = *(nameStudent + mov);
}
sum += *(ageStudent + mov);
mov++;
}
average = (double) sum / num;
cout << a << " Is youngest student and " << b << " Is oldest student " << endl << average << " is average age of students";
}

最佳答案

您将 young 初始化为 0。如果有一个学生的年龄小于 0,它只会改变 younga

不是对所有这些变量的初始值进行硬编码,而是从数组的第一个元素中获取它们。

if (num > 0) {
young = old = sum = *ageStudent;
a = b = *nameStudent;
}

然后您可以将循环更改为从 1 而不是 0 开始,因为您已经处理了数组的第一个元素。

顺便说一句,不需要 mov 变量,因为它总是包含与 i 相同的内容。请改用 *(ageStudent + i)

void check(string *nameStudent, int *ageStudent, int num) {
int i, young = 0, old = 0, sum = 0;
string a, b;
double average;
if (num > 0) {
young = old = sum = *ageStudent;
a = b = *nameStudent;
}
for (i = 1; i < num; i++){
if (*(ageStudent + i) < young) {
young = *(ageStudent + i);
a = *(nameStudent + i);
}
if (*(ageStudent + i) > old) {
old = *(ageStudent + i);
b = *(nameStudent + i);
}
sum += *(ageStudent + i);
mov++;
}
average = num ? (double) sum / num : 0; // prevent division by 0
cout << a << " Is youngest student and " << b << " Is oldest student " << endl << average << " is average age of students";
}

关于c++ - 为什么我的程序不打印字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087803/

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