"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Get a Float Result from Integer Division in C++?

How to Get a Float Result from Integer Division in C++?

Published on 2025-02-02
Browse:565

How to Get a Float Result from Integer Division in C  ?

Casting Integers to Floats for Accurate Division

In C , dividing two integers, such as in a/b, results in an integer quotient. To obtain a float result, one must specifically cast the operands to floats.

Problem Statement:

When using integer operands in a division operation, the result is truncated to an integer. How can one prevent this and maintain the integrity of the numbers?

Solution:

To remedy this issue and ensure a float result, cast the operands to floats:

float ans = (float)a / (float)b;

By explicitly converting the operands to floats, the division operation will produce a float result, preserving any decimal precision.

Example:

Consider the following code:

#include 
#include 
using namespace std;

int main()
{
  int a = 10, b = 3;
  float ans = (float)a / (float)b;
  cout 

Output:

3
3.333

As seen above, the casting ensures a float result, retaining the correct decimal precision.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3