由于数据类型使用不正确而导致计算不正确 [英] inaccurate calculation caused by inaccurate data type use

查看:108
本文介绍了由于数据类型使用不正确而导致计算不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<math.h>

int main(){
  int num,onum,numl=0,tem,nnum=0;    

  printf("Enter num: ");
  scanf("%d", &num);

  onum =num;

  while (num!=0){
    num = num/10;
    ++numl;
  }
  num = onum;

  while (num!=0){
    tem = num%10;

    nnum += pow(tem,numl);
    printf("%d",nnum);
    num /= 10    ;
  }

  if (nnum == onum){
    printf("is");
  }
  else{
    printf("not");
  }
}

可以与其他自恋数字配合使用.

works fine with other Narcissistic numbers .

但是当输入153,5 ** 3被错误地计数为124时,为什么呢?

but when input 153 , 5**3 is mistakenly counted to 124, why?

此问题与许多问题重复.下面的答案是最容易理解的答案.

This question is duplicate of many questions. And the answer below is the most easy-to-understand anwer.

在一句话中,错误的计算是由{错误的{数据类型使用情况}或{编译器}或{FPU}}引起的.

In one sentence, the inaccurate calculation is caused by {inaccurate {data type usage} or {compiler} or {FPU} }.

我通过将编译器更新为gcc 7.2来避免了错误.但是,解决问题需要整数的pow函数.

I avoided the error by updating my compiler to gcc 7.2 . But solving the problem needs a pow function for integer.

推荐答案

pow(在pow(tem,numl)中)是浮点函数.这意味着它返回一个double,绑定到浮点数的误差和舍入(如果pow返回124.999999,则对浮点计算没有影响,但由于截断而分配给整数时会起作用)

pow (in pow(tem,numl)) is a floating point function. It means that it returns a double, bound to floating point inaccuracy and rounding (if pow returns 124.999999 it has no impact for floating point computation, but it does when assigned to an integer because of truncation)

因此,依赖于pow的返回值可能有效,也可能无效(取决于值,FPU,编译器数学库).而且,有时它会发布一个稍微偏离的值"这一事实是该浮点精度问题的一种免费赠品.

So relying on the return value of pow may work, or may not (depends on the values, the FPU, the compiler math libraries). And the fact that "sometimes it issue a slightly off value" is a giveaway for that floating point inaccuracy issue.

由于您仅使用整数,因此我将使用整数幂运算,或者通过简单的循环或更复杂的算法(

Since you're working exclusively with integers, I would use integer exponentiation instead, either with a simple loop or with more complex algorithms (The most efficient way to implement an integer based power function pow(int, int))

这篇关于由于数据类型使用不正确而导致计算不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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