C-分区不起作用

标签 c math division

我实际上完全陷入困境,我不明白这个函数的行为:

#include <stdio.h>

typedef struct s_resolution
{
   int x;
   int y; 
   float fx;
   float fy;
} t_resolution;

typedef struct s_pixel_info
{
    int tablen;
    t_resolution resolution;
    char name;
    int line;
    int pos_suite[6];
    int suite[6];
} t_pixel_info;

void get_proportion_ratio(t_pixel_info DataB, t_pixel_info pix_info,
                           t_resolution *proportion)
{
    proportion->fx = (float)(DataB.resolution.x / pix_info.resolution.x);
    //I also tried without the cast
    proportion->y = (int)(DataB.resolution.y / pix_info.resolution.y * 100);
    //if (proportion->y != 100)
    printf("%d | %d | %d\n",proportion->y, DataB.resolution.y, pix_info.resolution.y);
}

int main()
{
  t_pixel_info DataB;
  t_pixel_info pix_info;
  t_resolution proportion;

  DataB.resolution.x = 5;
  pix_info.resolution.x = 10;
  DataB.resolution.y = 5;
  pix_info.resolution.y = 10;
  get_proportion_ratio(DataB, pix_info, &proportion);

}

DataB.resolution.y , pix_info.resolution.yproportion->y都是Int类型。
我的问题是我有这个结果:

0 | 5 | 10

该操作仅在结果为 100 时才有效...我一定错过了一些明显的东西,但我不知道是什么。

最佳答案

您的所有除法都是对整数进行的。采用这个表达式:

5 / 10 * 100

这组为:

(5 / 10) * 100

计算结果为 0:5/100,而 0 * 100 仍然是 >0。事后转换结果并不会改变它。

如果在除法之前先乘以 100 ,您将获得另外两位精度:

100 * 5 / 10

计算结果为 50:100 * 5500500/10 50 .

您还可以以浮点形式执行算术,例如

(double) 5 / (double) 10 * (double) 100

或者您可以只转换第一个操作数并让标准算术转换处理其余的操作数;结果是等效的:

(double) 5 / 10 * 100

无论哪种情况,结果都是50.0

关于C-分区不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348018/

相关文章:

c - <inttypes.h> 的良好介绍

Mathematica 矩阵对角化

python - 奇怪的错误: ZeroDivisionError: float division by zero

c++ - 如何计算位图大小?

c++ - 为什么我的 double 或 int 值在除法后总是 0?

javascript - 如何使用 javascript 每秒执行 60 次某事

c - 指向指针数组的指针

c - block 设备驱动程序 - 了解接收到的 ioctl

c - 在不更改 x87 寄存器的情况下进行十进制除法

我可以将 C 上的二维数组设置为(固定)(动态)吗?