Wednesday, 31 March 2021

c++ data type hackerrank basic data type 2nd problem

Since float has a precision of up to only 7 digits, it shows garbage values after its precision is exceeded.

Our double variable shows the correct number because it has a precision of 15 digits, while the number itself consists of 13 digits


Solution 1:

add header  library #include <bits/stdc++.h> and use fixed setprecision(n) in the code

cout<<fixed<<setprecision(3)<<d<<endl;
cout<<fixed<<setprecision(9)<<e<<endl;

Solution 2:

use printf:

printf("%.3f\n", f);
printf("%.9lf", z);


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

int main() {
    int a;
    long b;
    char c;
    float d;
    long double e;
    cin>>a>>b>>c>>d>>e;
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<fixed<<setprecision(3)<<d<<endl;
    cout<<fixed<<setprecision(9)<<e<<endl;
    
    return 0;
}


or

printf("%.3f\n", f);
printf("%.9lf", z);


No comments:

Post a Comment