S
S
Sergo Zar2021-12-19 20:55:48
C++ / C#
Sergo Zar, 2021-12-19 20:55:48

How to "normally" convert float to int?

There is one problem in this code - when numberLast is cast to the int type, the value for some reason turns into an integer but 1 less than necessary. Why is that? And how to fix it?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
  float massiv[3][3] = { {1.1, 2.2, 9.9}, {3.3, 4.4, 5.5}, {6.6, 7.7, 8.8} };
  cout << "Before: " << endl;
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      cout << massiv[i][j] << " ";
    }
    cout << endl;
  }

  cout << endl;
  cout << "After: " << endl;
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 3; j++)
    {
      float number;
      float numberLast;
      numberLast = modff((massiv[i][j]), &number);
      cout << (int)(numberLast*10) << " ";
    }
    cout << endl;
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-12-19
@Sergomen

This is the normal float to int conversion - rounded down.
Edit: Apparently the problem is that 0.9 can't be represented perfectly in a float. It actually stores something like 0.8999999.... Multiplying by 10 and rounding down will give you 8, not 9.
You should use round to nearest.

D
danSamara, 2021-12-19
@danSamara

First you need to decide what is "normal" for you.
You can round up:

  • Dropping the fractional part
  • To the big side
  • Downward
  • "Mathematically" - to a large one with a rounding error of 1/2
  • "Accounting" - to the nearest even, with a rounding error of 1/2

You use the first option, but others are possible. See round(), ceil(), floor(), and trunc() functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question