繁体   English   中英

简单乘法后获得错误的结果 - C ++

[英]Getting wrong results after simple multiplication - C++

因此,需要做的是:输入一个实数并打印小数点后的前4位数之和。 例如:我输入5.1010。 我到了需要将0.1010乘以10000以便它可以变成整数的点,但我得到的结果是1009而不是1010,之后一切都崩溃了。 如果有人能向我解释为什么会这样,我会永远感激不尽。

#include<iostream>
using namespace std;

int main()
{
  double n;
  cout<<"Enter a positive real number: ";
  do
  {
    cin>>n;
    if(n<=0) cout<<"The number must be positive, enter again: ";
  }while(n<=0);

    //storing the fractional part in a var
  int y=n;
  double fr=n-y;
  //turning the fractional part into an integer
  int fr_int=fr*10000;
  cout<<fr_int<<endl;

  //storing each of the digits in a var
  int a=fr_int/1000;
  int b=fr_int/100%10;
  int c=fr_int/10%10;
  int d=fr_int%10;

  cout<<"The sum of the first 4 digits is: " << a+b+c+d;
  return 0;
}

我认为你应该在转换之前添加0.5,因为编译将始终截断数字。

在C ++ 11中,您可以使用std :: round。

您可以按如下方式更改代码,然后它应该正常工作。

  n *= 10000;
  int Integer = n;

  int i = 4;
  int sum = 0;
  while(i--)
  {
    sum += (Integer%10);
    Integer /= 10;
  }
  std::cout << "The sum of the first 4 digits is: " << sum;

以下是输出: https//www.ideone.com/PevZgn

更新 :广义soln将使用std::string 但是,如果代码能够在用户提交非数字的情况下处理异常,那将是很好的。

#include <iostream>
#include <string>

int main()
{
  std::string Number;
  double tempNum = 0.0;

  std::cout << "Enter a positive real number: ";
  do
  {
    std::cin >> Number;
    tempNum = std::stof(Number);

    if(tempNum <= 0)
      std::cout << "The number must be positive, enter again: ";
  }while(tempNum <= 0);

  bool Okay = false;
  int sum = 0;
  int i = 4;

  for(const auto& it: Number)
  {
    if(Okay && i > 0)
    {
      sum += static_cast<int>(it - '0');
      --i;
    }
    if(it == '.') Okay = true;
  }
  std::cout << "The sum of the first 4 digits is: " << sum;

  return 0;
}

C ++中的浮点和双精度无法准确表示所有十进制数。 特别是0.1,它不能忠实地代表。

如果必须保证获得准确的结果,则应使用定点数学或bignumber库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM