PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] how to make 69.99*100 print 6999 instead of 6998?

 July 21, 2022     c++, double, floating-point, integer     No comments   

Issue

I want to have the right 6999 but the code prints 6998, is there any way to implement it in C/C++?

#include <iostream>
using namespace std;

int main() {
 double x = 69.99;
 int xi = x*100;
 cout << xi << endl;
 return 0;
}

Solution

Your compiler is probably using the IEEE 754 double precision floating point format for representing the C++ data type double. This format cannot represent the number 69.99 exactly. It is stored as 69.989999999999994884. When you multiply this value with 100, the result is slightly smaller than 6999.

When implicitly converting floating-point numbers to integers, the number is always rounded towards zero (positive numbers get rounded down, negative ones get rounded up).

If you don't want to always round the result towards zero, you can change the line

int xi = x*100;

to

long xi = lround( x*100 );

which will not always round the number towards zero, but will instead always round it to the nearest integer.

Note that you must #include <cmath> to be able to use std::lround.



Answered By - Andreas Wenzel
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing