-6

why it is printing as cout<<(4*(double)(r*r))<<endl; as integer as something wrong with my typecast. I have to take input r as an int input->1 output->4

and why
cout<<setprecision(2)<<ab2<<endl; rounding the answer at least it should give correct answer till two digits because i have set set precision 2 input->1 output->3.8

    #include<bits/stdc++.h>
    using namespace std;

    int main(){
        int t;
        cin>>t;
        while(t--){
            long long int r;
            cin>>r;
            double ab2 = 4*(double)(r*r) - double(0.25);
            cout<<4*(double)(r*r)<<endl;
            cout<<setprecision(2)<<ab2<<endl;
            cout<<ab2+0.25<<endl;

        }

    }
  • 2
    please be more precise on what is the output and what did you expect, currently it is rather unclear what you think is wrong with the output – 463035818_is_not_an_ai Jan 11 '19 at 22:25
  • 2
    `3.8` is two digits of precision. precision is not number of decimal places. – john Jan 11 '19 at 22:27
  • 1
    Unrelated: By themselves [`#include`](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) can lead you into a lot of trouble. Together they can combine into a terrifying, program-destroying monster. Exercise caution. – user4581301 Jan 11 '19 at 22:31

2 Answers2

1

I'm guessing you're going to see something more like what you are expecting with this code

int main() {
    cout << fixed << setprecision(2); // fixed notation and two decimal places
    int t;
    cin >> t;
    while (t--) {
        long long int r;
        cin >> r;
        double ab2 = 4 * (double)(r*r) - double(0.25);
        cout << 4 * (double)(r*r) << endl;
        cout << ab2 << endl;
        cout << ab2 + 0.25 << endl;

    }
}

Input

1 1

Output

4.00
3.75
4.00
john
  • 85,011
  • 4
  • 57
  • 81
0

why it is printing as cout<<(4*(double)(r*r))<<endl; as integer as

It is a double, so it is printing it as a double. It is however a double that represents a whole number.

and why cout<<setprecision(2)<<ab2<<endl; rounding the answer

Because you've used smaller precision than the value has significant digits.

eerorika
  • 232,697
  • 12
  • 197
  • 326