c - 在 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。
解决方案
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
推荐阅读
- linux - 如何解析 CURL 命令结果的输出?
- c# - 无法从“int”转换为 System.Windows.Form.ListViewItem.ListViewSubitem
- python - Numpy 中的向量化赋值
- concurrency - perl6 grep 类似程序并行
- lektor - 在主页上显示最近的博客活动
- ignite - Ignite TcpCommunicationSpi:slowClientQueueLimit 可以根据文档设置为与 messageQueueLimit 相同的值吗?
- android - Android 应用程序包 -> apk 不包含必需的本机库
- javascript - 我怎样才能调用反应状态不同的js
- java - 如何将属性文件中的所有值作为键传递给 hashmap
- scala - 在 CV 网格中为 Spark xgBoost 模型设置 scalePosWeight 参数