Home > other >  Problem with int to float typecasting and couting
Problem with int to float typecasting and couting

Time:02-05

#include <iostream>
 
using namespace std;
 
int main()
{
    int nominals[15] = {50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
    float numer;
    cin>>numer;
    numer = numer * 100;
    int numer2 = (int)numer;
    while(numer2 != 0)
    {
        for(int i = 0; i<15; i  )
        {
            if(numer2 >= nominals[i])
            {
                numer2 = numer2 - nominals[i];
                if(nominals[i] >= 100)
                {
                    cout<<nominals[i] / 100<<" ";
                }
                else
                {
                    float nominal = nominals[i] / 100;
                    cout<<nominal<<" ";
                }
                i--;
            }
        }
    }
}

Basically, what I've tried here is separating a given number to values present in the table nominals. With values >= 100 it works properly. However, with values < 100 it doesn't works at all, at least it doesn't cout it. Yet i can't debug it cause gdb doesn't work with it at all. Note the conversion taking place in the first part of main() function and converting int to float and dividing it by 100 after a value satisfies a certain criteria. Also, the program doesn't work with a dot, but partially does when a comma is present instead.

So far I've tried rewriting the code altogether, testing it on different platforms, to no avail. I have no idea how to get it to work, that's why I'm here.

And please, don't be too harsh, I'm a novice.

CodePudding user response:

Change

float nominal = nominals[i] / 100; // integer division

to

float nominal = nominals[i] / 100.0; // floating point division

Dividing one integer by another always produces another integer (any fractional part of the division is discarded).

  • Related