你能帮我买一些显示如何创建两个长号的减法吗? 我在网上找到了这段代码:
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
// the two "numbers" to be added. Make them as long as you like.
string numStr1;
string numStr2;
cout << "Enter 1st number: "; cin >> numStr1;
cout << "Enter 2nd number: "; cin >> numStr2;
// keeping track of which string is longest using references
string& rLongStr = numStr1.length() > numStr2.length() ? numStr1 : numStr2;
string& rShortStr = numStr1.length() <= numStr2.length() ? numStr1 : numStr2;
// initialize the sum with the long string but with space for a final carry at the beginning
string numStrSum = '0' + rLongStr;// the '0' in case of a final carry
// must go through the strings backwards since the least
// significant digit is at the end, not the beginning.
string::reverse_iterator r_itShort, r_itSum;
r_itShort = rShortStr.rbegin();// point to last "digit" in the short string
r_itSum = numStrSum.rbegin();// same for sum string
// add the "digits" one by one from end to beginning of the short string
while( r_itShort != rShortStr.rend() )
{
*r_itSum += *r_itShort - '0';// "add" the digits
if( *r_itSum > '9' )// must carry a one to the next "digit"
{
*(r_itSum + 1) += 1;
*r_itSum -= 10;
}
++r_itShort;// move back 1 character
++r_itSum;// in each string
}
if( numStrSum.at(0) == '0' )// if 1st character is stiil '0'
numStrSum.erase(0,1);// erase it
// output result
cout << numStrSum;
cout << endl;
return 0;
}
所以,我无法减少这两个数字。我试过这样的smt:
while( r_itShort != rShortStr.rend() )
{
*r_itSum -= *r_itShort + '0';
if( *r_itSum > '9' )
{
*(r_itSum + 1) -= 1;
*r_itSum += 10;
}
--r_itShort;
--r_itSum;
}
if( numStrSum.at(0) == '0' )
numStrSum.erase(0,1);
但它显示了我的相同。你能帮帮我,告诉我我做错了什么吗? 谢谢!
答案 0 :(得分:-3)
您可以使用iostream
/ cin
向cout
输入和输出float / double / integer类型,因此字符串解析不会有问题。你可以把它们当作双重类型。
如果您真的想将这些数字作为字符串,可以使用atof
将它们转换为浮点数。然后只需计算您需要的内容,并使用std::to_string
或直接打印。