當我打電話給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