【问题标题】:Question about typecast behavior in arithmetic关于算术中的类型转换行为的问题
【发布时间】:2022-10-13 18:11:44
【问题描述】:

我有以下代码。我的主要问题在于第 5 行。

int x1 = extRes1.at(1).toInt();   //A fairly large int value. This is from Qt, where extRes is a QStringList. the key is, the function returns an int value.
int x2 = extRes2.at(1).toInt();
int y1 = extRes1.at(2).toInt();
int y2 = extRes2.at(2).toInt();
double c = (double)(y2*x1-y1*x2)/(x1-x2);   //Typecasting, as I want this arithmetic to return a floating point properly.

我的问题是,第 5 行的类型转换的确切行为是什么?基于what I've found on the topic so far, 我相信第 5 行 RHS 的结果 "(y2 *x1-y1 * x2)/(x1-x2)" 用双精度表示。但是类型转换是否通过将算术中的所有单个元素(例如 y2、x1)转换为类型(在本例中为 double)来工作?还是仅通过转换最终解决方案的结果来工作?

我知道在技术层面上,我的问题可以通过将预先存在的整数转换为双精度数来解决。如果需要更多信息,请告诉我。

【问题讨论】:

  • 只有(y2*x1-y1*x2) 的结果是int 被转换为double。然后使用浮点除法将这个double 除以(x1-x2),得到double 结果。
  • 谢谢你。你能把这个放在答案中吗?
  • 是的,我会做的。

标签: c++ casting


【解决方案1】:

只有(y2*x1-y1*x2) 的结果int 被转换为double
这是由于强制转换运算符的优先级。

然后这个double使用浮点除法除以(x1-x2),产生double结果c

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 2019-12-31
    • 2015-10-14
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多