【发布时间】:2016-02-07 20:28:26
【问题描述】:
下面是我的 c++ 程序,用于将两个字符串(字符串中的整数)相乘并在字符串中生成整数结果。我相信这是由于 cout flush 问题。有人可以在打印答案之前解释如何在没有 endl 或任何文本字符串的情况下打印值。
#include <iostream>
using namespace std;
string multiply (string s1, string s2)
{
char str[10];
string ans="";
int m=s1.length();
int n=s2.length();
if (!s1.compare("0") || !s2.compare("0"))
return "0";
int *res = new int[m + n];
for (int i = m - 1; i >= 0; i--)
{
for (int j = n - 1; j >= 0; j--)
{
res[m + n - i - j - 2] += (s1[i] - '0') * (s2[j] - '0');
res[m + n - i - j - 1] += res[m + n - i - j - 2] / 10;
res[m + n - i - j - 2] %= 10;
}
}
for (int i = m + n - 1; i >= 0; i--)
{
if (res[i] != 0)
{
for (int j = i; j >= 0; j--)
{
sprintf(str,"%d", res[j]);
ans+=str;
}
return ans;
}
}
}
int main() {
cout << multiply("0", "0"); // Doesn't work - prints nothing.
/**cout << multiply("0", "0") << endl; //works!! This prints "0" correctly **/
return 0;
}
【问题讨论】:
标签: c++