dnyaneshwar muley
dnyaneshwar muley

Reputation: 43

issue with float value printing in cpp

#include <iostream>
#include<bits/stdc++.h> 
using namespace std;
int solve(int t){
    float ans = static_cast<float>(320)/100;
    cout<<fixed<<setprecision(2)<<ans;
}
int main(){
    int t=320;
    cout<<solve(t);
    return 0;
}

output:3.204745728

how should I get output as 3.20

Upvotes: 1

Views: 69

Answers (1)

john
john

Reputation: 87959

You are using cout twice, when you only want to output one thing. You are also outputting the return value of solve when you don't return anything from solve, this explains the extra digits that you see.

Either do the cout in solve or do it in main, don't do it in both places.

First way

#include <iostream>
using namespace std;
void solve(int t){
    float ans = static_cast<float>(320)/100;
    cout<<fixed<<setprecision(2)<<ans; // print the answer
}
int main(){
    int t=320;
    solve(t);
    return 0;
}

Second way

#include <iostream>
using namespace std;
float solve(int t){
    float ans = static_cast<float>(320)/100;
    return ans;                        // return the answer
}
int main(){
    int t=320;
    cout<<fixed<<setprecision(2)<<solve(t);
    return 0;
}

Another issue with your code is that you are passing the parameter 320 to solve, but you aren't using it there. You might want to change that

float ans = static_cast<float>(t)/100;

It's quite common for beginners to get confused between returning a value from a function, and printing a value in a function, but these are quite different things. The first code above prints the value in the function, the second code above returns the value from the function (and prints it in main).

Upvotes: 1

Related Questions