1
#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

  • 2
    Please read https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – Some programmer dude Jan 16 '21 at 06:41
  • 1
    You are invoking undefined behavior by not returning a value in `int solve()`, change to `void solve(int t)` and call it in `main` as `solve(t)`; – DarthQuack Jan 16 '21 at 06:44
  • "*how should I get output as 3.20*" Comment out the `cout` line in `main`. This will also remove the undefined behavior due to using the return value of `solve`, which `solve` forgot to return. – dxiv Jan 16 '21 at 06:57
  • 1
    @Someprogrammerdude FWIW this looks to be one of the rarer cases which is *not* a duplicate of the canonical question. – dxiv Jan 16 '21 at 06:59
  • 1
    @dxiv True, now that I see it again. But I'll bet there's some nice duplicate for the real issue as well. :) – Some programmer dude Jan 16 '21 at 07:08

1 Answers1

1

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).

john
  • 85,011
  • 4
  • 57
  • 81