標題說的是全部。給定半徑計算體積的數學是錯誤的,但面積的計算是正確的。
#define _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES
#include <stdio.h>
#include <string.h>
#include <math.h>
float radius[4][3];
int x = 0;
int main()
{
while (x < 4)
{
printf("Please enter Radius %d: ",(x 1));
scanf("%f", &radius[x][0]);
radius[x][1] = ((4 / 3) * M_PI * pow(radius[x][0], 3));
radius[x][2] = M_PI * pow(radius[x][0], 2);
x ;
}
x = 0;
while (x < 4)
{
printf("\n\rThe volume for a sphere with the radius %.2f is %.2f", radius[x][0], radius[x][1]);
printf("\n\rThe area for a circle with the radius %.2f is %.2f", radius[x][0], radius[x][2]);
x ;
}
return 0;
}
uj5u.com熱心網友回復:
4 / 3兩個運算元都有整數,因此執行整數除法。這會將結果截斷為 0,結果為 1。
使用浮點常量來執行浮點除法。
radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));
uj5u.com熱心網友回復:
在這一行: radius[x][1] = ((4 / 3) * M_PI * pow(radius[x][0], 3));
這個運算子(4 / 3)是一個整數除法,因為左右運算元都是整數 {4和3) 所以它會被截斷為 0。
4 / 3 = 1.33333333333333333...但結果被截斷,所以它會回傳1。
使用浮點:
radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));
或者將其float型別轉換為型別。
radius[x][1] = (((float)4 / 3) * M_PI * pow(radius[x][0], 3));
uj5u.com熱心網友回復:
除了從整數除法哪里去(4 / 3)是1到浮點除法,可以考慮使用一致的數學型別:
double radius[4][3];
radius[x][1] = ((4.0 / 3.0) * M_PI * pow(radius[x][0], 3));
radius[x][2] = M_PI * pow(radius[x][0], 2);
或者
#define M_PIf 3.1415926535897932f
float radius[4][3];
radius[x][1] = ((4.0f / 3.0f) * M_PIf * powf(radius[x][0], 3));
radius[x][2] = M_PIf * powf(radius[x][0], 2);
我會留下來double并利用先前的乘法而不是呼叫昂貴的pow()。
double radius[4][3];
radius[x][2] = M_PI * radius[x][0] * radius[x][0];
radius[x][1] = (4.0 / 3.0) * radius[x][2] * radius[x][0];
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335621.html
上一篇:計算二進制數中的0序列
