c - C 中的类型转换和括号的使用

标签 c casting parentheses

我有这些变量

distance = 945
speed = 614

我想获得以小时和分钟为单位的时间,所以我除以距离/速度以获得小时数。现在,如果我想要分钟作为整数,我有以下代码:

int minutes;
minutes = (float) (distance%speed) / speed * 60;

这个表达式给出了 32 分钟的值,但是,当我第一次尝试时,我想让代码更“可读”,所以我尝试了以下给出 0 的选项:

minutes = (float)  ( (distance%speed) / speed * 60 );
minutes = (float) ( (distance%speed) / speed  ) * 60;

注意括号是加的,而且是在不同的地方,所以为什么在我觉得没问题的地方用括号会干扰计算,在变量中设置0的值。我想这与类型转换过程有关,但括号位于应该使表达式更清晰的地方。

我的答案是正确的,程序运行正常,但我想了解这一点以备将来使用,因为我花了一点时间来研究括号。谢谢

最佳答案

so why using parentheses in places that look fine to me interfere with the calculation and sets the value of 0 in the variable.

那是因为额外的括号 () 会使您在第二个语句中对 float 的转换无效。

  • 在你的第一句话中:

分钟 = (float) (距离%速度)/速度 * 60;

这里首先评估(float) (distance%speed)

  • 但是在你的第二个陈述中:

(float) ( (distance%speed)/speed * 60 );

您的额外 () 导致 (distance%speed)/speed * 60 首先被评估,因此转换 (float) 变为无关紧要。

I wanted to make the code more "readable"

与“可读性”相关,虽然在这里添加更多括号肯定无济于事,但 Kingsley 的建议(添加单位)是一个好方法。例如,

int distance_m = 945;
int speed_kph = 614;

关于c - C 中的类型转换和括号的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35190918/

相关文章:

c - 为什么我没有收到将指针转换为 int 的警告?

sql - Oracle中缺少右括号

Java:何时在方法后面使用括号

c - 我如何正确地找出结构数组的大小?

C# 将对象列表中的对象转换为类型返回左手签名必须是变量错误

C:计算出的机器 epsilon 与 limit.h 不同

Java 泛型 : Array Casting

perl - 哪个 Perl 模块 'explains' 在命令行上提供了一个表达式?

c - 使用指针和数组打印 2 个数字之间的所有奇数

c++ - int fun(void **args) 并在调用函数时传递参数 fun(args),