Stoycho Vladikov
Stoycho Vladikov

Reputation: 53

Getting wrong results after simple multiplication - C++

So, what needs to be done is: enter a real number and print the sum of its first 4 digits after the decimal point. E.g.: I enter 5.1010. I get to the point where I need to multiply 0.1010 by 10000 so it can become an integer, but the result I'm getting is 1009 instead of 1010 and everything falls apart after that. I'd be forever thankful if someone can explain to me why does that happen.

#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;
}

Upvotes: 4

Views: 1345

Answers (3)

JeJo
JeJo

Reputation: 33092

You could simply change the code as follows, then it should be working.

  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;

Here is the output: https://www.ideone.com/PevZgn

Update:A generalized soln would be using std::string. However, would be great if the code is capable of handling exceptions in the case of non-numeric has been submitted by the user.

#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;
}

Upvotes: 2

Clearer
Clearer

Reputation: 2306

Floating points and doubles in C++ aren't able to represent all decimal numbers accurately. In particular, 0.1, it cannot represent faithfully.

If you must be guaranteed that you get accurate results, you should either use fixed point math or a bignumber library.

Upvotes: 0

Dina Bogdan
Dina Bogdan

Reputation: 4738

I think you should add 0.5 before casting because the compile will always truncate the number.

In C++11 you can use std::round.

Upvotes: 2

Related Questions