这是我的程序:
int main(){
struct Koordinaten {
float x;
float y;
}Vektor[3];
typedef struct Koordinaten Koordinaten;
float A[3], s, b;
for(int i = 0; i < 3; i++){
char d;
if(i == 0)
d = 'A';
if(i == 1)
d = 'B';
if(i == 2)
d = 'C';
printf("Please enter the coordinates of the %c vector:\nx: ", d);
scanf("%f", &Vektor[i].x);
printf("\ny: ");
scanf("%f", &Vektor[i].y);
printf("Values of the %c vector x: %f y: %f\n\n", d, Vektor[i].x, Vektor[i].y);
A[i] = sqrt(Vektor[i].x * Vektor[i].x + Vektor[i].y * Vektor[i].y);
printf("The length of the vector %c is: %f\n\n", d, A[i]);
}
s = 1/2 * (A[0] + A[1] + A[2]);
printf("s = %f\n", s);
b = sqrt(s * (s - A[0]) * (s - A[1]) * (s-A[2]));
printf("The area is: %f", b);
}
如您所见,我想取三个 vector 并给出 vector 的面积。由于带有 s 变量的行,它完美地工作。我的程序只给了我 0 的 s 值,但它必须是 7.5!
最佳答案
在你的代码中
s = 1/2 * (A[0] + A[1] + A[2]);
是相同的
s = (1/2) * (A[0] + A[1] + A[2]);
^^^^^^--------------------------This is an integer division, with a result 0,
so, 's' will always have a value 0.
你需要把它改成
s = 1.0/2 * (A[0] + A[1] + A[2]);
^^^^^^-----------------------------now this is floating point division.
以确保浮点除法。
关于c - 为什么我的 C 程序不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58994006/