g++ warning with -Wconversion flag

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Oct 2009
Posts: 23
Reputation: raigs is an unknown quantity at this point 
Solved Threads: 0
raigs raigs is offline Offline
Newbie Poster

g++ warning with -Wconversion flag

 
0
  #1
Nov 9th, 2009
I get this g++ warning when I use the -Wconversion flag. Anybody know how to write this "correctly" ?

a.cpp:15: warning: conversion to ‘float’ alters ‘double’ constant value
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. float VAR1(float VAR2)
  6. {
  7. int VAR3 = (int)(VAR2 * 1.045 * 1.55); // Result must be an int
  8. float VAR4 = (float)(VAR3 + 0.95); // Result must be float ending in .95
  9.  
  10. return VAR4; // Return a float ending in .95
  11. }
  12.  
  13. int main(void)
  14. {
  15. printf("%.2f", VAR1(25.95)); // printf a float ending in .95
  16.  
  17. return 0;
  18. }
Reply With Quote Quick reply to this message  
Join Date: Jan 2009
Posts: 343
Reputation: JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice JasonHippy is just really nice 
Solved Threads: 63
JasonHippy's Avatar
JasonHippy JasonHippy is offline Offline
Posting Whiz
 
0
  #2
Nov 9th, 2009
It's because the literal value (25.95) that you are passing into your call to the function VAR1 is automatically treated as a double, but your function takes a float as a parameter. So you're getting a warning about it.

If you pass the variable like this:
  1. printf("%.2f", VAR1(25.95f)); // printf a float ending in .95
The f at the end of the literal value will ensure that the value is treated as a float and not a double and should stop the warning from occurring.

in fact considering this is C++ you should really be using std::cout instead of printf in line 15 too! :
  1. cout << setprecision(.2) << VAR1(25.95f);

Note: in order to use setprecision with cout, you also need to include iomanip after iostream..:
So after you've included iostream, add the following:
  1. #include <iomanip>

Cheers for now,
Jas.
Last edited by JasonHippy; Nov 9th, 2009 at 9:57 am.
If you're into metal, check out my new band at:
http://www.myspace.com/kinasis
Now booking gigs for 2010....
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 285 | Replies: 1
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC