Reputation: 3
This problem is not working for a test case specified below. I think ther must be some errror in multiplication in the long double numbers
#include<bits/stdc++.h>
using namespace std;
string multiplyStrings(string , string );
int main() {
int t;
cin>>t;
while(t--)
{
string a;
string b;
cin>>a>>b;
cout<<multiplyStrings(a,b)<<endl;
}
}// } Driver Code Ends
/*You are required to complete below function */
string multiplyStrings(string s1, string s2) {
int sign = 1;
bool up1 = false;
bool up2 = false;
char ch1;
char ch2;
stringstream ss1(s1);
stringstream ss2(s2);
if(s1[0]=='-') {
sign = -1;
up1 = true;
}
if(s2[0]=='-') {
sign = -1;
up2 = true;
}
long double a, b, prod;
if(up1 == true && up2 == true) {
ss1 >> ch1 >> a;
ss2 >> ch2 >> b;
prod = a * b;
}
else if(up1 == true) {
ss1 >> ch1 >> a;
ss2 >> b;
if(a==0 || b==0) {
prod = 0;
} else {
prod = a * b * sign;
}
}
else if(up2 == true) {
ss1 >> a;
ss2 >> ch2 >> b;
if(a==0 || b==0) {
prod = 0;
} else {
prod = a * b * sign;
}
}
else {
ss1 >> a;
ss2 >> b;
prod = a * b*1.0;
}
ostringstream strNew;
strNew << prod;
string newSt = strNew.str();
return newSt;
}
On using this test case for the program Input: 4416 -333
Its Correct output is: -1470528
And Your Code's output is: -1.47053e+06 Please help me out with the code?? and give the solution to it.
Upvotes: 0
Views: 78
Reputation:
Just use
strNew << fixed;
or
strNew.setf(ios_base::fixed, ios_base::floatfield);
before output. It helps show floating-point value as a decimal in any case.
Upvotes: 1
Reputation: 9058
Your output is in exponential format because your data is of type long double. User EOF gave you a hint:
strNew << fixed << prod;
However, if I were your professor, I would be testing your program with some extra-large numbers that result in values too large to be expresses in even a long double without rounding. You may want to ask if you need to support arbitrarily large values.
If you do, then you need an entirely different algorithm, probably one that implements the solution in a fashion similar to long arithmetic done by hand on paper.
If you don't understand what I mean, I recommend a google search of:
c++ number of significant digits long double
You're likely to have 30-something significant digits, so you could accurately display a number consisting of 30(ish) 9s, but not 40(ish) 9s.
Try it with your program (once you fix the output). Multiply 40 9s by 1 and see what you get.
Now, your prof may not actually test that. But if you're going through the work of multiplying the individual digits in this fashion instead of just using stoi() * stoi() on the two values, there's a reason for it.
Upvotes: 0