gpt4 book ai didi

c - 我们如何从c中的函数返回一个数组?

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

我们如何从函数返回一个数组,我不知道该怎么做???有三辆车,每辆车在 parking 场最多停放 24 小时,我们必须通过创建一个评估成本的函数来找到每辆车的成本..??

#include <stdio.h>
#include <math.h>
#include <conio.h>
int calculateCharges(float hours[]);

int main() {
float hours[3];
int i;
for (i = 0; i <= 2; i++) {
printf("Enter the hours you parked for car : %d\n", i + 1);
scanf_s("%f", &hours[i]);
}
hours[i] = calculateCharges(hours[]);

printf("%-10s%-10s%-10s\n", "Cars", "Hours", "Charge");
for (i = 0;i <= 2;i++) {
printf("%-10d%-10.2f%-10.2f\n", i + 1, hours[i], calculateCharges(hours));
}

_getch();
return 0;
}

int calculateCharges(float hours[]) {

float cost[3];
int i;
for (i = 0; i <= 2; i++) {

if (hours[i] <= 3) { //if car parked for 3 or less hours it cost 2$
cost[i] = 2;
}
else if (hours[i] > 3 && hours[i] < 24) { //if car parked for more than 3 or less then 24 hours it cost 0.5$for each extra hour$
cost[i] = 2 + ((hours[i] - 3) / 2);
}
else if (hours[i] == 24) { //if hours = 24 hours 10$
cost[i] = 10;
}
else {
cost[i] = 0; //else its an error value zero cost
}

return cost[i];
}

}

最佳答案

您可以传入另一个数组来返回成本,而不是使其成为本地数组。你的方法看起来像这样:

int calculateCharges(float hours[], float costs[], int num) {
...
for(i=0;i<num;i++) {
...
costs[i] = 2;

关于c - 我们如何从c中的函数返回一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33741976/

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