关于C除法的意外结果 [英] An unexpected result about divide in C

查看:99
本文介绍了关于C除法的意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是输出输入数字的平均值及其取反。

My goal is to output the average of the input number and its reversal.

当我输入974时,结果是726.0,而不是726.5。我已经考虑了很长时间了,但是我仍然找不到答案。

When I input 974, the result is 726.0 instead of 726.5. I have think about this problem for long time but I still cannot get the answer.

希望有人可以帮助我。
非常感谢!

Hope someone can help me. Thank you very much!

#include <stdio.h>
int main(void)
{
    int N, D1, D2, D3;
    double aver;

    scanf("%d", &N);
    D1 = N % 10;
    D2 = ((N - D1) / 10) % 10;
    D3 = (N - D1 - D2) / 100;
    aver = (D1*100 + D2*10 + D3 + N) / 2;

    printf("%lf", aver);

    return 0;
}


推荐答案

在您的代码中, N D1 D2 D3 ,都是 int s,因此计算方式

In your code, N, D1, D2, D3, all are ints, so the calculation

(D1*100 + D2*10 + D3 + N) / 2;

作为整数算术执行,后来结果提升为 double 。因此,结果只是 int 值的双重表示形式。

is performed as integer arithmetic and later the result is being promoted to double. So, the result is just a double representation of an int value.

要强制执行浮点运算,


  1. 将操作数数据类型更改为 double float

  2. 将至少一个操作数转换为 float

  1. Change the operand data type(s) to double or float.
  2. Cast at least one operand to float.

这篇关于关于C除法的意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆