How can a floating-point number be printed with more precision? - c++

So i was attempting to code this question Link and i developed the logic and i started coding it. The code is shown below, but there is an issue with it. When i gave the code the following input (Image 1), the output came out to be 2.22582e+007, whereas the correct accepted output is 22258199.500000. What changes should i make in the data type to amend this error. How can i change the notation. Please bear with me as my knowledge of data types is limited.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n,l;
cin >> n;
cin >> l;
vector<float> v;
vector<float> b;
for(int i=0; i<n; i++){
int x;
cin >> x;
v.push_back(x);
}
sort(v.begin(),v.end());
if(v[0]!=0){
b.push_back(v[0]);
for(int i=1; i<n; i++){
b.push_back((v[i] - v[i-1])/2.0);
}
}else if(v[0] == 0){
for(int i=1; i<n; i++){
b.push_back((v[i] - v[i-1])/2.0);
}
}
sort(b.begin(), b.end());
cout << b[b.size()-1];
}

You can use std::cout << std::setprecision(std::numeric_limits<float>::max_digits10) to output the value in a round-trippable format. (This will need headers <limits> and <iomanip>).
If that doesn't work, try also replacing float with double.

You're going to want to use iomanip.
#inlcude <iomanip>
cout<<fixed<<setprecision(6)
fixed will disable the scientific notation.
setprecision will allow you to be as precise as you want.

This resolved the issue.
link
The issue primarily was that the notation of the output was scientific and sometimes the online judges do not accept that, hence to change the notation from scientific to fixed and to other forms, the following code snippet can be used.
Either you can increase the precision or you can change the notation. Either of the latter cases can help.
#include <iostream>
#include <sstream>
int main()
{
std::cout << "The number 0.01 in fixed: " << std::fixed << 0.01 <<
'\n'
<< "The number 0.01 in scientific: " << std::scientific <<
0.01 << '\n'
<< "The number 0.01 in hexfloat: " << std::hexfloat << 0.01
<< '\n'
<< "The number 0.01 in default: " << std::defaultfloat <<
0.01 << '\n';
double f;
std::istringstream("0x1P-1022") >> std::hexfloat >> f;
std::cout << "Parsing 0x1P-1022 as hex gives " << f << '\n';
}
output of the given code - click here

Related

#include <cmath> stopped working in C++20?

Summarize the problem:
My goal is to generate odd numbers up to a limit, store them in a vector then output the square of them.
Describe what you've tried:
So far, I used the #include < cmath > at the start before int main(), then I used a couple of if statements to check whether the limit is zero, if so I output an error message. If the limit is >0 then I squared the odd numbers using pow(num,2) however, this does not work and gives wrong answer. For example, it gives the square of 13 as 600ish, that is obviously wrong. Please give advice. My full code is here, it is very simple so I did not put much comments in there:
#include<iostream>
#include<format>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int limit{};
cout << "Enter a limit of odd integers: \n";
cin >> limit;
vector<int>oddnumb(limit);
if (limit == 0)
{
cout << "You MUST enter a number>0, then restart the program. \n";
return 0;
}
if (limit > 0)
{
cout << "Odd numbers are as follows: \n";
for (size_t i{}; i < limit-1; ++i)
{
oddnumb[i] += ++i;
cout << oddnumb[i] << endl;
}
cout << "Squared odd numbers follow: \n";
for (size_t i{}; i < limit - 1; ++i)
{
oddnumb[i] += ++i;
cout << pow(oddnumb[i],2) << endl;
}
}
I've written up a working version of what you want to do. I urge you to figure it out yourself first, that's the best way to learn, and then check your version against what I've got here. Note that this is certainly not the best way to do it. But I wrote it in a way that should be easy to understand. In programming there are lots of ways to tackle any problem, the best way is arguably... the way that works! Good luck in your journey with C++!
#include <cmath>
#include <iostream>
#include <vector>
int main()
{
double input{};
while (input < 1)//validate that input is greater than 0 here by looping if it isn't
{
std::cout << "Enter a limit of odd integers: ";
std::cin >> input;
if (input < 1)//if a valid range is entered this is never shown
{
std::cout << "Enter a valid range. Greater than 0. \n\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::vector<double> oddNumbers{};
std::cout << "Odd numbers:\n";
//notice we're starting this loop at 1, since 0 is even we just avoid it
for (double i = 1.0; i <= input; i += 2.0) //you can add more than just 1 to i
{
oddNumbers.push_back(i);// here we're putting the value of i at the back of the vector
std::cout << i << " squared is " << pow(i, 2.0) << '\n';
//we could avoid using a vector by printing the squared value of i within this loop
}
std::cout << "Squared Odd Numbers:\n";
//we do need to start this loop at 0 to access the first element of the vector
for (unsigned int i = 0; i < oddNumbers.size(); i++)
//we also increase i by just one each time to access each element we stored
{
std::cout << pow(oddNumbers[i], 2.0) << '\n';
}
return 0;
}

my c++ codes in xcode stopped working properly

I have this code:
#include <iostream>
using namespace std;
double sqrt(double n)
{
double x;
double y = 2; //first guess is half of the given number
for (int i = 0; i<50; i++)
{
if (n>0)
{
x = n / y;
y = (x + y) / 2;
}
if (n==0)
{
return 0;
}
}
return y;
}
int main()
{
cout << "Square Root Function" << endl;
double z=0;
while (true)
{
cout << "Enter a number = ";
cin >> z;
if (z<0)
{
cout<<"enter a positive number"<<endl;
continue;
}
cout <<"the square root is "<< sqrt(z) << endl;
}
return 0;
}
and it would show this result:
Square Root Function
Enter a number = 12
the square root is: 3.4641
but now the code is showing these results:
Square Root Function
1 //my input
Enter a number = the square root is 1
2 //my input
Enter a number = the square root is 1.41421
It seems like the cout will only show up first if an endl was added after the string. This just started happening recently. Is there a way I can fix this to show the proper output?
std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.
You can also use std::cout << std::endl, which writes a line break and then flushes, thats the reason your code shows this behavior.
Change your int main() to
int main(){
std::cout << "Square Root Function" << std::endl;
double z=0;
while (true){
std::cout << "Enter a number = " << std::flush
/*^^^^^^^^^^*/
std::cin >> z;
if (z<0){
std::cout << "enter a positive number" << std::endl;
continue;
}
std::cout << "the square root is " << sqrt(z) << std::endl;
}
}
EDIT: The XCode Problem Since you use XCode another thing could cause trouble. It seems like XCode doesn't flush buffers until a line break; flushing doesn't help. We had several questions about it lately (e.g. C++ not showing cout in Xcode console but runs perfectly in Terminal). It seems to be a bug in a XCode version.
Try to flush your buffer as described by me and try to compile it using terminal. If it works there your code is fine and it's an XCode issue.

std::_throw_out_of_range occurs from nowhere

I'm an absolute beginner in c++. Literally. It's just been a week.
Today I was writing a program to test how many iterations are needed to make a certain number palindromic.
Here is the code:
#include <iostream>
#include <string>
#include <algorithm>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers 1 to 1000
*/
using namespace std;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
int i=0;
while (numsum.value.compare(numsumreverse.value) !=0)
{
reversenum=num;
reversenum.reverse();
numsum.value=to_string(stoll(num.value,0,10)+stoll(reversenum.value,0,10));
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
}
int main()
{
number temp;
int i;
for (i=1; i<1001; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
return 0;
}
It goes on smooth for numbers upto 195. But, in case of 196 I get an error.
It says:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoll
I cannot make out what to do. I tried starting from 196 but the error persisted. Any help will be greatly appreciated. :)
UPDATE: This time I tried to do it using ttmath library. But arghs! It again stops at 195 and doesn't even report an error! I might be doing something foolish. Any comments would be appreciated. Here's the updated code:
#include <iostream>
#include <string>
#include <algorithm>
#include <ttmath/ttmath.h>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers 1 to 1000
*/
using namespace std;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
template <typename NumTy>
string String(const NumTy& Num)
{
stringstream StrStream;
StrStream << Num;
return (StrStream.str());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
ttmath::UInt<100> tempsum, numint, reversenumint;
int i=0;
while (numsum.value.compare(numsumreverse.value) !=0)
{
reversenum=num;
reversenum.reverse();
numint=num.value;
reversenumint=reversenum.value;
tempsum=numint+reversenumint;
numsum.value=String<ttmath::UInt<100> >(tempsum);
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
}
int main()
{
number temp;
int i;
for (i=196; i<1001; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
return 0;
}
UPDATE: It's solved. Some research suggested that 196 might be a Lychrel Number. And the result I was getting after implying the ttmath library is just reassuring that my algorithm works. I have tried it out for all the numbers upto 10000 and it gave out the perfect results. Here is the final code:
#include <iostream>
#include <string>
#include <algorithm>
#include <ttmath/ttmath.h>
#include <limits>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers inside a desired range
*/
using namespace std;
string LychrelList;
int LychrelCount=0;
class number
{
public:
string value;
void reverse();
};
void number::reverse()
{
std::reverse(value.begin(),value.end());
}
template <typename NumTy>
string String(const NumTy& Num)
{
stringstream StrStream;
StrStream << Num;
return (StrStream.str());
}
void palindrome(number num)
{
string n=num.value;
number reversenum, numsum, numsumreverse;
reversenum=num;
reversenum.reverse();
numsum.value=num.value;
numsumreverse.value=numsum.value;
numsumreverse.reverse();
ttmath::UInt<100> tempsum, numint, reversenumint;
int i=0;
while ((numsum.value.compare(numsumreverse.value) !=0) && i<200)
{
reversenum=num;
reversenum.reverse();
numint=num.value;
reversenumint=reversenum.value;
tempsum=numint+reversenumint;
numsum.value=String<ttmath::UInt<100> >(tempsum);
numsumreverse.value=numsum.value;
numsumreverse.reverse();
num.value=numsum.value;
i++;
}
if (i<200) cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num.value << endl;
else
{
cout << "A solution for " << n << " could not be found!!!" << endl;
LychrelList=LychrelList+n+" ";
LychrelCount++;
}
}
int main()
{
cout << "From where to start?" << endl << ">";
int lbd,ubd;
cin >> lbd;
cout << endl << "And where to stop?" << endl <<">";
cin >> ubd;
cout << endl;
number temp;
int i;
for (i=lbd; i<=ubd; i++)
{
temp.value=to_string(i);
palindrome(temp);
}
if (LychrelList.compare("") !=0) cout << "The possible Lychrel numbers found in the range are:" << endl << LychrelList << endl << "Total - " << LychrelCount;
cout << endl << endl << "Press ENTER to end the program...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin,s);
cout << "Thanks for using!";
return 0;
}
It's a really awesome community. Special thanks to Marco A. :)
UPDATE AGAIN: I've devised my own add() function that cuts the program's dependency on external libraries. It resulted in a smaller executable and faster performance too. Here is the code:
#include <iostream>
#include <string>
#include <algorithm>
#include <limits>
/* This program calculates the steps needed
to make a certain number palindromic.
It is designed to output the values for
numbers inside a desired range
*/
using namespace std;
string LychrelList;
int LychrelCount=0;
string add(string sA, string sB)
{
int iTemp=0;
string sAns;
int k=sA.length()-sB.length();
int i;
if (k>0){for (i=0;i<k;i++) {sB="0"+sB;}}
if (k<0) {for (i=0;i<-k;i++) {sA="0"+sA;}}
for (i=sA.length()-1;i>=0;i--)
{
iTemp+=sA[i]+sB[i]-96;
if (iTemp>9)
{
sAns=to_string(iTemp%10)+sAns;
iTemp/=10;
}
else
{
sAns=to_string(iTemp)+sAns;
iTemp=0;
}
}
if (iTemp>0) {sAns=to_string(iTemp)+sAns;}
return sAns;
}
void palindrome(string num)
{
string n=num;
string reversenum, numsum, numsumreverse;
numsum=num;
numsumreverse=numsum;
reverse(numsumreverse.begin(),numsumreverse.end());
int i=0;
while ((numsum.compare(numsumreverse) !=0) && i<200)
{
reversenum=num;
reverse(reversenum.begin(),reversenum.end());
numsum=add(num,reversenum);
numsumreverse=numsum;
reverse(numsumreverse.begin(),numsumreverse.end());
num=numsum;
i++;
}
if (i<200) cout << "The number " << n << " becomes palindromic after " << i << " steps : " << num << endl;
else
{
cout << "A solution for " << n << " could not be found!!!" << endl;
LychrelList=LychrelList+n+" ";
LychrelCount++;
}
}
int main()
{
cout << "From where to start?" << endl << ">";
int lbd,ubd;
cin >> lbd;
cout << endl << "And where to stop?" << endl <<">";
cin >> ubd;
cout << endl;
string temp;
int i;
for (i=lbd; i<=ubd; i++)
{
temp=to_string(i);
palindrome(temp);
}
if (LychrelList.compare("") !=0) cout << "The possible Lychrel numbers found in the range are:" << endl << LychrelList << endl << "Total - " << LychrelCount;
cout << endl << endl << "Press ENTER to end the program...";
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string s;
getline(cin,s);
cout <<endl << "Thanks for using!";
return 0;
}
You guys here have helped me a lot to find my own way. Thanks everyone. :)
You're overflowing long long since the last two valid values of num.value and reversenum.value are 7197630720180367016 and 6107630810270367917 which, added together, are way above the maximum size of a long long (9223372036854775807 on my machine). That will yield a negative value and spoil your next call to stoll
std::out_of_range is thrown if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.
(reference)
If you're trying to get the next smallest palindrome, you should use another approach like the one I explained here.
You can find a Live Example here
If you prefer to/must continue with your approach you should either do the addition manually on the strings or use a bigint library (again take a look at here and modify the plusOne() function to your liking)
From http://www.cplusplus.com/reference/string/stoll/
If the value read is out of the range of representable values by a long long, an out_of_range exception is thrown.
The ll data type cant handle the string length. My debugger tells me 196 breaks on the value
std::stoll (__str=\"9605805010994805921-\", __idx=0x0, __base=10)
The long long is too small.
You might want to do the addition on the strings themselves, without resorting to a numeric type.

Why arrays do not print whole table?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int d,m;
int districts=3;
int months = 12;
double sales[districts][months];
for (d=0 ; d < districts; d++)
{
for(m=0; m< months; m++)
{
cout << "Enter sales for District " << d+1 << ":" << " and Month " << m+1 << ": ";
cin >> sales[districts][months];
}
}
cout << "\n\n\n";
cout << setw(40) << "Months\n";
cout << setw(26) << "1 2 3 4 5 6 7 8 9 10 11 12\n";
for (d=0; d < districts ; d++)
{
cout << "District " << d+1;
for(m=0; m< months; m++)
{
cout << ": " << sales[districts][months];
}
}
return 0;
}
This code after running takes only two input values from user and after that a window appear displaying message a problem caused the program to stop working correctly.
There are no compilation errors and I am unable to find the problem. Is there anyone who can help?
You use variables d and m as counter-variables for your loops, but inside the loops you use the maximum value for both of them (districts and months) instead of d and m.
Change this: cin >> sales[districts][months]; to this: cin >> sales[d][m];
Also, this: cout << ": " << sales[districts][months]; to this: cout << ": " << sales[d][m];.
The term sales[districts][months] refers to a particular element sales[3][12], which also happens to be out of bounds for the 2-d array.
The reading loop is repeatedly reading a value to sales[districts][months], i.e. to sales[3][12], which - since array indexing starts at zero in all dimensions, doesn't exist. That gives undefined behaviour.
The output loops are repeatedly outputting the same value, which also gives undefined behaviour.
A common symptom (but not the only possible one) of undefined behaviour is abnormal program termination - and you are seeing an example of that.
There is also the wrinkle that
int districts=3;
int months = 12;
double sales[districts][months];
involves a variable length array (VLA) which is a feature of C (from the 1999 C standard or later) but is not valid C++. If that construct works for you, your compiler supports a non-standard extension.

How to read the entire value of a double using cin?

long double m;
cout << "enter double: "; cin >> m;
cout << "m = " << m <<endl;
Input:
enter double: 1.546640625
Output:
m = 1.54664
I have to convert into a binary with point, and when I read numbers like 2.359375000
Output:
m = 2.35938
And it works, but I think the problem is the zero in 1.546640625
You have read the whole value of the double. The problem is with the cout. It by default rounds the value to 6 digits after the decimal point.
To set the precision cout uses, use setprecision from <iomanip>:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double d;
cin >> d;
cout << setprecision(10) << d << endl;
return 0;
}