I
I
Ilya2014-09-15 18:36:08
C++ / C#
Ilya, 2014-09-15 18:36:08

Why does static_cast return wrong value?

Good day. I study C++ according to R. Laforet's book "OOP in C++".
There was a problem in the program

#include <iostream>
#include <clocale>
using namespace std;
int main()
{
  setlocale(LC_CTYPE, "rus");
  float a, c, k;
  int b, z;
  cout << "Введите количество фунтов: " << endl;
  cin >> a;
  b = static_cast<int>(a);
  c = a - b;
  c *= 20;
  z = static_cast<int>(c);
  k = c - z;
  k *= 12;
  k = static_cast<int>(k);
  cout << "Эквивалентная сумма в старой форме записи: J" <<b<<"."<<z<<"."<<k<< endl;
  return 0;
}

If the user enters for example 8.65, then after the lines
c *= 20;
z = static_cast<int>(c);

it turns out that z=12. Although it should actually be 13.
Let c=0.65*20, then z = static_cast(13). And accordingly, when selecting the integer part from 13, we should get 13. Help me understand the problem.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Taratin, 2014-09-15
@Quirel

0.65 cannot be represented in memory as exactly 0.65
Use double instead of float

J
jcmvbkbc, 2014-09-15
@jcmvbkbc

0.65 = 65 / 100 = 13 / (2 * 2 * 5). This fraction cannot be represented in the final form as a binary number, since its denominator contains numbers other than 2. Therefore, calculations with its participation are approximate.

A
AxisPod, 2014-09-16
@AxisPod

So use the functions specially designed for this from math.h (cmath). And even double will not help you in all situations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question