c - 为什么我的 C 程序不能正常工作?

标签 c arrays struct

这是我的程序:

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/

相关文章:

c - 如何从 C 中的函数返回多个值?

android - For循环多个数组并保留空行

arrays - 如何在 Matlab 中将结构体的叶子作为向量返回?

python - 在 struct.unpack 格式字符串中间切换字节序

struct - 错误 : struct Type is not an expression

c - 用C语言将数据写入文件[序列化]

c - 仅使用数组的链表实现

c - struct passwd 是内存泄漏的来源 - 如何正确释放?

c - 初始化程序必须是常量

ios - '数组 <(对象)>' is not convertible to ' bool 值'