2014-10-28 29 views
0

当我打电话给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; 
} 
+3

尝试在调用它们之前声明你的函数,或者在'main'之前定义它们。例如,在'main'之前,放置'float getinfo();'。我怀疑你编译时,你可能看到过一些你忽略的警告信息? – lurker 2014-10-28 00:26:48

+1

顺便说一句:你确定你有一个C编译器吗?因为我在那里检测MS-ISMS('#define _CRT_SECURE_NO_WARNINGS'' #include '),这让我猜你正在使用VC++,因此可能实际上不是C. – Deduplicator 2014-10-28 00:35:43

+0

关于如下行的代码:float radius = 0;这是初始化一个浮点数,因此,为了避免一堆转换,行应该是这样的:float radius = 0.0f; – user3629249 2014-10-28 17:22:24

回答

2

线

radius = getinfo(); 

定义函数getinfo()之前出现。 C是有用的语言,它会假设你打算定义一个返回整数的函数。事实上,你定义它返回一个浮动后不会阻止它从这个信念。

添加

float getinfo(); 

某处之上main()(或移动到main()底部)。

+0

与返回浮点数的其他两个函数相同。 – 2014-10-28 00:32:51

+2

任何像样的编译器都会在这样的隐式声明上发出警告,至少如果你礼貌地问 - “Wow -Wextra -pedantic-errors -std = c11”应该是一些编译器选项。 – Deduplicator 2014-10-28 00:33:52