我实际上完全陷入困境,我不明白这个函数的行为:
#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.y
和proportion->y
都是Int
类型。
我的问题是我有这个结果:
0 | 5 | 10
该操作仅在结果为 100 时才有效...我一定错过了一些明显的东西,但我不知道是什么。
最佳答案
您的所有除法都是对整数进行的。采用这个表达式:
5 / 10 * 100
这组为:
(5 / 10) * 100
计算结果为 0
:5/10
是 0
,而 0 * 100
仍然是 >0
。事后转换结果并不会改变它。
如果在除法之前先乘以 100
,您将获得另外两位精度:
100 * 5 / 10
计算结果为 50
:100 * 5
为 500
,500/10
为 50
.
您还可以以浮点形式执行算术,例如
(double) 5 / (double) 10 * (double) 100
或者您可以只转换第一个操作数并让标准算术转换处理其余的操作数;结果是等效的:
(double) 5 / 10 * 100
无论哪种情况,结果都是50.0
关于C-分区不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47348018/