Basically my code is about calculating equilateral triangle perimeter. Given values are these:
3
2.5 3 5.15
First number defines how many triangles there are and the numbers in second line are each triangle's side length.
Here's my code:
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <algorithm>
#include <cstdlib>+
using namespace std;
double Strik(double a);
int main()
{
int n;
cin>>n;
double arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
cout<<fixed<<setprecision(2)<<arr[i]<<" "<<Strik(arr[i])<<endl;
}
return 0;
}
double Strik(double a){
double s = ((a*a)*sqrt(3))/4;
return s;
}
Cout needs to be like this:
2.5 2.71
3 3.90
5.15 11.48
But I get this:
2.5 2.71
3.00 3.90
5.15 11.48
Please help
std::setprecision
specifies the maximum number of digits to use and if you want to get N digits all the time you need to use std::fixed
.
#include <iostream>
#include <iomanip>
int main()
{
double a = 3.5;
std::cout << std::fixed;
std::cout << std::setprecision(4);
std::cout << a << "\n";
return 0;
}
And now the output is 3.5000
.
Opposite from std::fixed
is std::defaultfloat
and in the first column you need std::defaultfloat
but in the second column you need std::fixed
so this is the way to go for you:
cout << defaultfloat << setprecision(2) << arr[i] << " ";
cout << fixed << Strik(arr[i]) << endl;
Check out live
UPDATE
If, as said in one of the comments, you want to output number 13.6, then you need to increase precision like this:
cout << defaultfloat << setprecision(3) << arr[i] << " ";
cout << fixed << setprecision(2) << Strik(arr[i]) << endl;