Answer the question
In order to leave comments, you need to log in
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
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.
First you need to decide what is "normal" for you.
You can round up:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question