在C中将整数除法转换为double

use*_*429 0 c casting

为什么代码

double slope = (double)changeY/changeZ 
Run Code Online (Sandbox Code Playgroud)

将斜率设置为0.0,当我在程序中时,changeX = 20并且更改Y = 10(两个整数)?

Lun*_*din 8

听起来你使用的是错误的变量.试试这个:

int changeX = 20;
int changeY = 10;

double slope = (double)changeY/changeX;
Run Code Online (Sandbox Code Playgroud)

强制转换运算符()的优先级高于/.此表达式将评估为:

  • 投到changeY一个double.
  • 隐式转换changeXdouble.如果一个操作数是double,那么另一个操作数也被平衡到一个double(这被正式称为"通常的算术转换").
  • 划分两个操作数.结果将是双倍的.
  • 将此临时"result-double"存储到另一个名为slope的双精度中.