C++ 我在这个程序中遇到了一个双重乘法错误
此问题不适用于下面指定的测试用例。我想长的双数乘法一定有错误C++ 我在这个程序中遇到了一个双重乘法错误,c++,C++,此问题不适用于下面指定的测试用例。我想长的双数乘法一定有错误 #include<bits/stdc++.h> using namespace std; string multiplyStrings(string , string ); int main() { int t; cin>>t; while(t--) { string a; string b; cin>&g
#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;
}
#包括
使用名称空间std;
字符串多路复用字符串(字符串,字符串);
int main(){
int t;
cin>>t;
而(t--)
{
字符串a;
b串;
cin>>a>>b;
库塔;
ss2>>ch2>>b;
prod=a*b;
}
else if(up1==true){
ss1>>ch1>>a;
ss2>>b;
如果(a==0 | | b==0){
prod=0;
}否则{
产品=a*b*符号;
}
}
else if(up2==true){
ss1>>a;
ss2>>ch2>>b;
如果(a==0 | | b==0){
prod=0;
}否则{
产品=a*b*符号;
}
}
否则{
ss1>>a;
ss2>>b;
产品=a*b*1.0;
}
ostringstream strNew;
strNew您的输出是指数格式的,因为您的数据是long double类型。用户EOF给了您一个提示:
strNew << fixed << prod;
您可能有30位左右的有效数字,因此您可以准确显示由30(ish)9组成的数字,而不是40(ish)9
用你的程序试试(一旦你修正了输出),用40 9乘以1,看看你得到了什么
现在,你的教授可能不会真正测试这一点。但是如果你正在以这种方式将各个数字相乘,而不是对两个值使用stoi()*stoi(),那么这是有原因的。只要使用
strNew << fixed;
在输出之前。它有助于在任何情况下将浮点值显示为十进制。使用strNew spoiler:-1.47053e+06
是-1470528
的另一种表示法,最后一个数字四舍五入,出于好奇,什么是双乘法错误?你绝对确定浮点算术是正确的选择吗这里的离子?看起来你在处理“大整数”,像这样的问题通常用整数来解决。
strNew << fixed;
strNew.setf(ios_base::fixed, ios_base::floatfield);