0

我正在做家庭作业,我遇到了一些奇怪的事情。我有三个文件:Lab3.c、Lab3.h 和 driver.c。driver.c 正在从 Lab3.c 调用一个方法,但未能将值传递给该方法。

// code from driver.c
float cyRad, cyHt;
printf("Enter a radius for the cylinder: ");
scanf("%f", &cyRad);
printf("%f\n", cyRad);
printf("Enter a height for the cylinder: ");
scanf("%f", &cyHt);
float cyVol = cylinder(cyRad, cyHt);
printf("Cylinder volume: %f\n", cyVol);

// code from Lab3.c
float cylinder(float radius, float height) 
{
    printf("%f %f %f\n", M_PI, height, radius);
    return M_PI * height * pow(radius, 2);
}

// code from Lab3.h
#ifndef __LAB3_H
#define __LAB3_H

extern void sphere(float radius, float *surface, float *volume);
extern float volCylinder(float radius, float height);
extern double sumFloats(double x[], int numFloats);
extern double sine(float angle);

#endif

这是输出:

Enter a radius for the cylinder: 13
13.000000
Enter a height for the cylinder: 45
3.141593 0.000000 0.000000
Cylinder volume: 0.000000

我不知道为什么它没有将值传递给方法cylinder。任何和所有的帮助将不胜感激。

4

1 回答 1

1

调用函数时必须有一个原型在作用域内,否则假定它返回int并且它的参数类型是未知的。当将浮点数传递给具有未知参数类型的函数时,它们作为双精度值传递,这将导致函数中的虚假值(行为未定义,因此理论上任何事情都可能发生,尽管实际发生的情况取决于实现,但它不会是你想要的)。

在多文件程序中进行声明的最佳方法是为每个 .c 文件创建一个 .h 文件;.h 文件声明了 .c 文件中定义的函数(和其他全局变量)。然后#include .h 文件到任何使用这些全局变量的文件中......包括伴随的 .c 文件。

于 2013-04-07T00:39:07.847 回答