当我打电话给getinfo()
时,我得到一个8位的常数值,1位数值,9位2位数值,10位3位数值。等等。在函数中,按预期打印该值,但在尝试读取主方法中的值时,该值如上所述。C错误导致函数常量返回值
任何想法为什么会发生这种情况?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main(){
float radius = 0;
float height = 0;
float cylvolume = 0;
float spherevolume = 0;
displaymyinfo();
radius = getinfo();
printf("\n r = %f", radius);
height = getinfo();
printf("\n h = %f", height);
cylvolume = compute_cylinder_volume(radius, height);
spherevolume = compute_sphere_volume(radius);
printf("h = %f", height);
printf("\n A cylinder with radius %f and height %f = %f cubic inches", radius, height, cylvolume);
printf("\n Volume of sphere with radius: %f is %f cubic inches", radius, spherevolume);
_getch();
return 0;
}
int displaymyinfo(){
printf("*********************\n");
printf("*Info was here *\n");
printf("*and here*\n");
printf("*even here *\n");
printf("*********************\n");
return 0;
}
float getinfo(){
float y = 0;
do{
printf("\n Enter a number: ");
scanf("%f", &y);
} while (y <= 0);
printf("%f", y);
return (y);
}
float compute_cylinder_volume(float r,float h){
float vol = 0.0;
vol = 3.14 * r * r * h;
return vol;
}
float compute_sphere_volume(float rad){
float vol = 0.0;
vol = 4.0/3.0 * 3.14 * rad * rad * rad;
return vol;
}
尝试在调用它们之前声明你的函数,或者在'main'之前定义它们。例如,在'main'之前,放置'float getinfo();'。我怀疑你编译时,你可能看到过一些你忽略的警告信息? – lurker 2014-10-28 00:26:48
顺便说一句:你确定你有一个C编译器吗?因为我在那里检测MS-ISMS('#define _CRT_SECURE_NO_WARNINGS'' #include'),这让我猜你正在使用VC++,因此可能实际上不是C. –
Deduplicator
2014-10-28 00:35:43
关于如下行的代码:float radius = 0;这是初始化一个浮点数,因此,为了避免一堆转换,行应该是这样的:float radius = 0.0f; – user3629249 2014-10-28 17:22:24