gpt4 book ai didi

无法输入全天数据并累计总计

转载 作者:行者123 更新时间:2023-11-30 16:39:14 24 4
gpt4 key购买 nike

我遇到了一个错误,不允许我插入所有必需的数据。我确信我的 for 循环设置正确。我不太确定我缺少什么,但如果有人可以查看我的代码,我将非常感激!

我正在使用 Dev C++。

#include <stdio.h>




float loadArray(float *) ;

float calcTotal(float *); // calc total sales

int main()
{
//declare variables

float sales[7];
float weeklyS;
float total;
float totalS;
float highest;

//since these are pointers in the func, u need an &
sales[7] = loadArray(&weeklyS);

total = calcTotal(&totalS); // when calling a pointer use a & to send the address
printf("Total of the week is: %.2f",totalS);

//calcHighest(odom,odom2,milesDrvn,avgMPG);


return 0 ;

}



float loadArray(float *weeklyS)
{
float sales;
int x;

for ( x = 0; x < 7; x++)
{

// have user enter the following
printf("Enter sales for day %d: ",x + 1);
scanf("%d",&*weeklyS);

}

return sales;
}


float calcTotal(float *totalS)
{

float total = 0 ;
int x;

for ( x = 0; x < 7; x++)
{
total += *totalS;
*totalS++;

}




return total; /// return the accumulator
}

我在代码中声明了一些注释来解释什么是做什么的,但我不太确定为什么这段代码没有按应有的方式运行。我已将所有变量声明为 float ,我相信我也已正确处理我的指针并使用 * 和 & 正确调用它们。

最佳答案

以下不是完整的答案,只是对单个函数的更正,并带有大量注释:

原代码:

float loadArray(float *weeklyS)   
{
float sales;
int x;

for ( x = 0; x < 7; x++)
{
// have user enter the following
printf("Enter sales for day %d: ",x + 1);
scanf("%d", weeklyS);
}

return sales;
}

更正后的代码:

给“神奇”数字一个有意义的名称

#define DAYS_IN_WEEK 7

在“main()”中,传递一个指向sales[]数组的指针。

loadArray( sales );

修改原型(prototype)和“main()”中的调用以匹配此签名

void loadArray(float *sales)   
{
// keep the scope of a variable to the minimum
for ( int x = 0; x < DAYS_IN_WEEK; x++)
{
static char *day[] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};

// have user enter the daily sales
printf( "Enter sales for %s: ", day[x] );

// check for errors on calls to system functions
// note: 'sales+i' advances to pointer 'sales'
// by the length of each 'float' entry
// times the value in 'i'
// compare the returned value to '1'
// because that is the number of format specifiers
// use the format specifier '%f' because the input
// is to be converted to a 'float' value
// input sales amount
if( 1 != scanf( "%f", sales+i ) )
{ // then error occurred

// output your error message
// and the system error text
// to 'stderr'
// note: 'perror()' is found in 'stdio.h'
perror( "scanf failed" );

// note: 'exit()' and EXIT_FAILURE found in 'stdlib.h'
// unrecoverable error, exit the program
exit( EXIT_FAILURE );
} // end handling error
} // end for each days' sales
} // end function: loadArray

关于无法输入全天数据并累计总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47126342/

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