首页 > 解决方案 > 在 C 中“固定”大角度

问题描述

我需要能够比较 C 中 45 的倍数的角度(输入始终以度为单位)。

我已经编写了基本角度 0,45,90,135,180 的代码......但我也可以得到像 2070 这样的大角度,它与 90 相同。

我该怎么做?(对不起,如果这是一个非常简单的问题,我只是进入这个问题)

到目前为止,我已经尝试将角度转换为弧度并使用正弦函数。但问题是我无法使用==运算符比较它们。

到目前为止,这是我学会在 C 中比较值的唯一方法

double direction;
scanf("%d", &direction);

int x = sin(direction * 0.0174533);
//Wanted to use the == operator, so I thought I'd assign the sin to an int.

if (x == 1) {
    someInstruction();
}

问题是当我把它变成一个 int 时,这个值变成了 0 而不是 1。

标签: c

解决方案


You don't need to calculate the sine of the angle if you like to compare them. Actually it will give you headaches because exact equality of floating point values has its own problem. I'm not going deeper in it, if you're interested the research is left as an exercise for you.

Instead I'd like to introduce the "modulo" operator to you. This operator does a integer division and returns the remainder. In C and derived languages the operator is "%".

So you let the user input the angle as integer and calculate the remainder of the division by 360: int remainder = input % 360;

Examples:

input remainder
   0    0
 135  135
2070  270
3645   45 

推荐阅读