Division In C++ and java?

The premise of the question is wrong because it is based on a misunderstanding. C++’s auto is a compile time construct. It cannot infer a type based on runtime information. In your example, the type of z in this code is float:

auto z = a/b;

This is because that is the type of the expression a/b, given that both a and b are of type float.

The issue is that std::cout is not printing any decimal places for a whole floating point number such as 2.0. That is all. But you can tell it to do so. For example,

std::cout << std::fixed << std::setprecision(4);

Here’s a working example

#include <iostream>
#include <iomanip>

int main() {
    float a = 4;
    float b = 2;
    auto z = a / b;
    std::cout << std::fixed << std::setprecision(4);
    std::cout << z << std::endl;



Leave a Comment