我完成了我在C书中找到的一个程序,但我遇到了一些问题。 我刚刚完成,但我一直收到这个错误 错误1错误C2440:'功能' :无法转换为双倍[15]'到' 为什么我会收到此编译器错误?
void arrayRead(double, int*);
void arrayList(double, int*);
void arraySum(double, int*, int*);
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<ctype.h>
int main()
{
int num, sum = 0;
double array[15];
printf("How many doubles (numbers) would you like in the array (20 max)?\n");
scanf("%d", &num);
printf("Thank you! Now give me %d different doubles (numbers) please!\n", num);
arrayRead(array, &num);
printf("Here are all of your integers again!\n");
arrayList(array, &num);
arraySum(array, &num, &sum);
printf("The sum of these numbers = %d\n", sum);
return 0;
}
void arrayRead(double array[], int* num)
{
for (int i = 0; i < *num; i++)
{
scanf("%lf", &array);
}
}
void arrayList(double array[], int*num)
{
for (int i = 0; i < *num; i++)
{
printf("%.2f\n", array);
}
}
void arraySum(double array[], int*num, int* sum)
{
for (int i = 0; i < *num; i++)
{
*sum = array + *sum;
}
}
答案 0 :(得分:0)
最好在任何#include语句之后放置原型, 以防原型使用头文件中定义的内容
数组的大小必须是正数,
所以使用'%u'输入正数
并将max
变量定义为无符号
函数的参数和调用这些函数时传递的参数需要具有匹配的类型(或者函数类型是传递类型的'提升'。
由于数组是doubles
,所有引用也应该是double
,就像sum
变量一样。
适当的水平空白区域使代码更容易阅读
不要#include头文件,这些内容没有被使用。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
//#include <ctype.h>
// prototypes
void arrayRead( double*, unsigned );
void arrayList( double*, unsigned );
void arraySum ( double*, unsigned, double* );
int main( void )
{
unsigned num;
double sum = 0.0;
printf( "How many doubles (numbers) would you like in the array (20 max)?\n" );
if( 1 != scanf( "%u", &num ) )
{
perror( "scanf for size of array failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
// need to add check that user entered value is in range 1...20
double array[ num ];
printf( "Thank you! Now give me %u different doubles (numbers) please!\n", num );
arrayRead( array, num );
printf( "Here are all of your integers again!\n" );
arrayList( array, num );
arraySum( array, num, &sum );
printf("The sum of these numbers = %lf\n", sum);
return 0;
} // end function: main
void arrayRead( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
scanf("%lf", &array[i]);
}
} // end function: arrayRead
void arrayList( double array[], unsigned num )
{
for ( unsigned i = 0; i < num; i++ )
{
printf("%.2f\n", array[i]);
}
} // end function: arrayList
void arraySum( double array[], unsigned num, double* sum )
{
for ( unsigned i = 0; i < num; i++ )
{
*sum = array[i] + *sum;
}
} // end function: arraySum
以下是答案代码的简单输出:
How many doubles (numbers) would you like in the array (20 max)?
5
Thank you! Now give me 5 different doubles (numbers) please!
1 1 1 1 1
Here are all of your integers again!
1.00
1.00
1.00
1.00
1.00
The sum of these numbers = 5.000000
答案 1 :(得分:-1)
您声明的函数具有与您定义的函数不同的签名。
在使用double
代替double *
的声明中要小心。它不一样。
当您调用arrayRead
函数和公司时,编译器只会看到声明的函数,因为定义的函数在调用之后。所以参数不匹配。
顺便说一句,在定义的函数中你忘了写索引。您正在使用指针,这无法正常工作。您需要在每个循环中编写array[i]
。