Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Apologies if my question is vague, I'm very new to this, but I need to convert an integer value to a float value in code, but I keep receiving the error
conversion from ‘int’ to ‘float’ may change value




This is the code in question

#include <stdio.h>  
void money_convertor(int cash)
{
	float Y = cash- 16;
    float Ye = C * 5;
    float Yen =  Ce/9;
    float Cost =  Yen + 900.1f;
    printf("cash Yen Cost\n---------------------------------------------\n%f  %f   %f\n", cash, yen, cost);
}


What do I add or change?

What I have tried:

First time coding for university, so really really lost. Help appreciated!
Posted
Updated 28-Sep-21 2:40am

How many more times are you going to ask this same question? We have explained (more than once) how to cast a float to an int and how to create a float value from an int. In the above code it is quite simple:
C++
void money_convertor(int cash)
{
	float Y = (float)cash- 16.0f;
// or another way
    float Y = (float)(cash- 16);

But you should not be using float types for financial calculations as they are inherently prone to rounding errors.
 
Share this answer
 
Comments
Member 15373566 28-Sep-21 5:54am    
This is my first question here...
Richard MacCutchan 28-Sep-21 5:59am    
Well the question is oddly similar to those posted by Member 15370412 - Professional Profile[^]. Maybe you are classmates.
float values aren't necessarily accurate, because of the way they are stored, so converting from a int to a float can in some cases lose you data (because a 32bit int takes the same space as a float, but has "more digits").

To get rid of the error, just cast the result, so the system knows you are sure about what you are trying to do:
float Y = (float) (cash - 16);
 
Share this answer
 
To fix such a compiler complain, replace
Quote:
printf("cash Yen Cost\n---------------------------------------------\n%f %f %f\n", cash, yen, cost);
with
C"
printf("cash Yen Cost\n---------------------------------------------\n%d  %f   %f\n", cash, yen, cost);


Your code, however, has also other problems.
 
Share this answer
 
Even all above is correct I would see the correct solution by changing the input type.
C++
void money_convertor(float cash)
Reasons:
1. you read what the code will do: some float calculation
2. it removes the compiler warning
3. currency calculation has always some float values ($ or €)

The third point I see as the most important, but the first is the computer science main reason.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900