我正在尝试使用向量进行非常大的乘法,并且在运行算法时我一直遇到问题。
vector<vector<int>> finalresult;
vector<int> currentrow;
int carry=0, workingnum=0, innerval =0, curnt=0, j=0;
for (auto an = a.rbegin(); an != a.rend(); ++an)
{
for (auto bn = b.rbegin(); bn != b.rend(); ++bn)
{
curnt = (*an) * (*bn);
if (curnt > 10 && carry ==0)
{
carry = curnt / 10;
currentrow.push_back(curnt % 10);
}
if (curnt < 10 && carry ==0)
{
currentrow.push_back(curnt);
}
if (curnt < 10 && carry >0)
{
if ((curnt + carry) < 10)
{
currentrow.push_back(curnt + carry);
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
}
finalresult.push_back(currentrow);
for (int i = 0; i < currentrow.capacity(); i++)
{
currentrow.pop_back();
}
for (int i=0; i < j; i++)
{
currentrow.push_back(0);
}
j++;
}
每次运行此代码时,如果它遇到内部if语句之一,如curnt&lt; 10和carry == 0,它会push_back弯曲,但是然后它也会在else部分再次执行。我无法理解为什么它也会在其他部分发生。 (我知道那是因为调试而发生的事情)任何人都可以对此有所了解吗?
答案 0 :(得分:0)
你有:
if (curnt < 10 && carry >0)
{
if ((curnt + carry) < 10)
{
currentrow.push_back(curnt + carry);
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
无论您在if
行之前执行了什么操作,都会执行else
块或if
块。
<强>简化强>
您可以替换
if (curnt > 10 && carry ==0)
{
carry = curnt / 10;
currentrow.push_back(curnt % 10);
}
if (curnt < 10 && carry ==0)
{
currentrow.push_back(curnt);
}
if (curnt < 10 && carry >0)
{
if ((curnt + carry) < 10)
{
currentrow.push_back(curnt + carry);
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
}
else
{
workingnum = curnt + carry;
carry = workingnum / 10;
currentrow.push_back(workingnum % 10);
}
通过
curnt += carry;
carry = curnt / 10;
currentrow.push_back(curnt % 10);