Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-11 01:00:02
Original
470 people have browsed it

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;
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template