How to make a double have always three decimal points? C++ - c++

I'm coding a program that takes user inputs and get the average of it. I need the average to always have three decimal points.
float didn't work.
some tutorials online advised to use setprecision() and fixed. That won't work because I don't know how long the number is gonna be.
Do you recommend converting the number into a string, get the length, and convert it back to double and use: setprecision(string.length+3)
Thanks

Try this :
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float ex[] = { 0.12345, 1.2345, 12.345};
cout << setprecision(3) << fixed;
for(int i = 0; i < 3; ++i)
cout << ex[i] << endl;
return 0;
}
which gives the following output:
0.123
1.235
12.345

I recommend using the full precision of double during your calculations, and then display your final result with three decimal places.

#include <iostream>
#include <iomanip> // header file for setprecision()
using namespace std;
int main()
{
double input[4] = {1.000 , 2.0000 , 3.00 , 5.235 };
double answer = 0 , sum = 0 ;
int count = 0;
for(int i = 0; i < 3; ++i)
{
sum+=input[i];
count++;
}
answer = sum/count;
cout.precision(3);
cout << answer << endl;
return 0;
}

Related

Output is correct but SPOJ gave me wrong answer

Quick question. This is the code that I wrote to finish a problem in SPOJ. The output is correct but it gives me wrong answer. Whats wrong with my code? This is the link to the question: https://www.spoj.com/problems/SUMUP/
#include <iostream>
#include <iomanip>
using namespace std;
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
cout<< setprecision(5) << c << '\n';
}
int main()
{ int n, z, t;
scanf("%d", &t);
const int NUMS = t;
int bobo[NUMS];
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
return 0;
}
This is the input:
5
1
2
3
4
5
This is my output:
0.33333
0.42857
0.46154
0.47619
0.48387
In the lines:
for(z = 0; z < NUMS; z++){
scanf("%d", &bobo[n]);
cal(bobo[n]);
}
You should use z instead of n when calling scanf() and cal()
SPOJ expected output seems to require trailing zeroes, which the setprecision(5) function removes from c output if there's any. To keep the trailing zeroes you can add left << setfill('0') << setw(7) in your cout to indicate that there should be at least 7 characters presents in your output line (two characters for '0.' and 5 decimal places) and if there're fewer characters, it will fill to the left side with '0's, adding back the trailing zeroes required.
cout << left << setfill('0') << setw(7) << setprecision(5) << c << '\n';
Another more elegant solution is to use printf instead
printf("%.5Lf\n",c);
void cal(int n){
long double a, b, c;
a = (n*n) + n;
b = 2.0 *(n*n + n + 1.0);
c = a / b;
printf("%.5Lf\n",c);
}

Counting and getting highest number of digits after decimal

I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}

Rounding 23.428 into 23.4

I need to round the answer 23.428 and get 23.4.
I did a little search about it and I may need to include a line float round (s) but I did it and CODEBLOCKS gives me an error.
Note: the file Information.txt contains numbers 7.5 305.5 4.09 4
My code is:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
float m, k, kk;
int n;
float s;
ifstream fd("Information.txt");
fd >> k >> m >> kk >> n;
k = k / 100;
m = m * k;
kk = kk * m;
s = kk / n;
/*s=((((k/100)*m)*kk)/n);*/
fd.close();
ofstream fr ("Rezults.txt");
fr << s;
fr.close();
return 0;
}
You can just multiply the number by 10, round it and then divide by 10 again:
float x = 23.428;
x = std::round(10.0*x);
x /= 10.0;
Floating-point values (i.e. floats) usually aren't stored in base 10, but when you display their values they get converted to base 10 because that's what most of us are used to. Output streams (std::cout and the fr in the example) do this conversion, with a default precision of 6 digits. To display 3 digits, just change the precision:
#include <iostream>
#include <iomanip>
#include <fstream>
int main() {
float num = 23.428;
std::cout << std::setprecision(3) << num << '\n';
std::ofstream fr("Rezults.txt");
fr << std::setprecision(3) << num << '\n';
return 0;
}

Why output showing 0 instead of 0.0?

I declared an array of 10 elements and initialized it with 0.0 .. 9.9 , its output is perfect except 0.0 has been changed into 0, why is it so?
#include <iostream>
using namespace std;
int main(void)
{
int const SIZE = 10;
double number[SIZE] = {0.0,1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
for(int i(0) ; i < SIZE ; i++)
{
cout << number[i] << endl ;
}
system("PAUSE");
}
Thanks,
output:
0 //it should be 0.0 not 0//
1.1
2.2
.
.
.
9.9
std::cout by default will output up to 6 digits, which in this case is one (the zero) since no decimals are needed. std::cout << (double)1.0; would display 1, for instance. You can use std::setprecision from the <iomanip> header and std::fixed to keep the decimal.
#include <iostream>
#include <iomanip>
int main(void)
{
int const SIZE = 10;
double number[SIZE] = {0.0,1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
std::cout << std::setprecision(1) << std::fixed;
for(int i(0) ; i < SIZE ; i++)
{
std::cout << number[i] << std::endl ;
}
}
There are lots of helpful i/o manipulators. Here's a reference to check it out.
“0.0” and “0” are two numerals for the same number. A double stores only the number1; it does not store the original numeral.
When the source text of a C++ program contains a numeral such as 0.0 or 1.1, the compiler converts it from that numeral (which is a string of characters) to a double. The double format only represents numbers, not the strings they came from. So, a zero in double is just zero; it is not “0” or “0.0” or “0.000”. When you print it, there is no way for software that prints a double to know whether the original numeral was “0” or “0.0”. It just prints it according to the rules for printing a double.
By default, a double value of zero is printed as “0”. If you wish it to be printed differently, you can use I/O manipulators to ask that it be formatted differently. For example, after you #include <iomanip>, you can use std::cout << std::setprecision(1) << std::fixed; to set the floating-point output format to one digit in a fixed (versus scientific) format. Then printing a double value of zero will produce “0.0”.
1 Except, for zero, double can distinguish +0 and –0 (when IEEE 754 is used for floating-point).
That is simply how cout works by default. To change that, you can either:
use the precision() method:
cout.precision(1);
for(int i(0) ; i < SIZE ; i++)
{
cout << number[i] << endl ;
}
Use setprecision():
#include <iomanip>
cout << setprecision(1) << fixed;
for(int i(0) ; i < SIZE ; i++)
{
cout << number[i] << endl ;
}
If you really need to output 0.0 rather than 0, look into #include <iomanip>
The normal format will use a representation a compact as possible in most cases. Since binary floating point numbers are normalized, they don't represent any trailing digits. If you want to have an extra fractional position, you might want to use these flags:
std::cout << std::fixed << std::setprecision(1);
The entire program would look like this:
#include <iomanip>
#include <iostream>
int main()
{
int const SIZE = 10;
double number[SIZE] = {0.0,1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9};
std::cout << std::fixed << std::setprecision(1);
for(int i(0) ; i != SIZE ; ++i)
{
std::cout << number[i] << '\n';
}
std::cin.ignore();
}

Calculation not outputting expected answer

I'm trying to work out the arctan of a number using the formula:
arctan(x) = x - x^3/3 + x^5/5 - x^7/7...
I have to calculate it to 20 decimal places. The answer should be 0.78539....
This is the code I have written, including some debugging statements. The problem is in the calculation I think but I just can't see it. Could someone point me in the right direction please?
EDIT : Can't use the atan function, has to be manually calculated using a double variable from user input.
#include <iomanip>
#include <cstdlib>
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double x;
int i;
int j;
int y=3;
cout<<"Please enter the number you wish to calculate the arctan of:"<<endl;
cin>>x;
//Calculate arctan of this number
cout<<x;
cout<<"\n";
cout<<y;
cout<<"\n";
cout<<"Start\n";
x=x-(pow(x,y)/y);
y=y+2;
cout << setprecision (20) << x;
cout<<"=x before loop\n";
cout<<y;
cout<<"=y before loop\n";
for(i=0;i<9;i++)
{
x=x+(pow(x,y)/y);
cout<<x;
cout<<"=x1 in loop\n";
y=y+2;
cout<<y;
cout<<"=y1 in loop\n";
x-(pow(x,y)/y);
cout<<x;
cout<<"=x2 in loop\n";
y=y+2;
cout<<y;
cout<<"=y2 in loop\n";
}
return 0;
}
Well, your x is changing! You probably want to use a different variable to store the value computed so far and the argument to your function. That said, don't expect to precise outputs because all those computations involve rounding.
This line:
x-(pow(x,y)/y);
might have something to do with your problem.
I would strong advise you use the inbuilt atan function, it is more than likely been well optimised for you architecture, as well as being a standard function recognised by most C++ programmers.
#include <cmath>
#include <iostream>
int main()
{
double d;
std::cout << "enter number" << std::endl;
std::cin >> d;
std::cout << "atan of: " << d
<< " is " << std::atan(d)
<< std::endl;
return 0;
}
I agree with #Mystical. I don't think you're going to get 20 digits of precision out of a double. I think you need a long double (if that exists on your system) or, perhaps you need to implement your own big-num class...