Home >Backend Development >C++ >How to Get a Floating-Point Result from Integer Division in C ?

How to Get a Floating-Point Result from Integer Division in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 01:00:02522browse

How to Get a Floating-Point Result from Integer Division in C  ?

Dividing Integers for a Floating-Point Result

Despite the use of a float variable to store the result, integer division can result in a truncated output. To overcome this issue while maintaining the input variables as integers, consider the following solution:

Cast the operands to floats explicitly:

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

This casting operation forces the compiler to perform floating-point division, ensuring a floating-point result even when the operands are integers. The example below demonstrates the expected behavior:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
  int a = 10, b = 3;
  float ans = (float)a / (float)b;  // Explicit casting to floats
  cout << fixed << setprecision(3);
  cout << ans << endl;  // Floating-point result
  return 0;
}

The above is the detailed content of How to Get a Floating-Point Result from Integer Division in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn