jus*_*bie 1 c++ string integer c++11
这是我一直在努力的:
输入 2 个正整数(最多 100 位)。
比较两个整数。
注意:这 2 个整数可以包含前导零。(这意味着您必须先删除零)
因为 100 位太长,所以我使用string数据类型。
但是在我下面的程序中,它只是返回'='
我调试它并发现for循环不起作用。
我的代码:
#include <iostream>
#include <string>
using namespace std; // I know this is bad but it's just a small program
char compareBigInterger(string str1,string str2)
{
while (str1[0] != 0) str1.erase(0, 1);
while (str2[0] != 0) str2.erase(0, 1);
char answerHold {'='};
if (str1.size() > str2.size())
{
answerHold = '>';
}
else if (str1.size() < str2.size())
{
answerHold = '<';
}
else
{
for (int i = 0; i < str1.size(); i++)
{
if (int(str1[i] - 48) < int(str2[i] - 48)) // 48 = '1' - 1
{
answerHold = '<';
break;
}
else if (int(str1[i] - 48) > int(str2[i] - 48))
{
answerHold = '>';
break;
}
}
}
return answerHold;
}
int main()
{
string str1;
string str2;
cin >> str1 >> str2;
cout << char{compareBigInterger(str1, str2)};
}
Run Code Online (Sandbox Code Playgroud)
线条
while (str1[0] != 0) str1.erase(0, 1);
while (str2[0] != 0) str2.erase(0, 1);
Run Code Online (Sandbox Code Playgroud)
将删除字符串中的所有字符,因为该值0用作字符串的结束标记。
要与字符零进行比较,您应该使用字符文字'0'(用 包围的字符'')。此外,循环应该是“字符为零时循环”以删除零。
while (str1[0] == '0') str1.erase(0, 1);
while (str2[0] == '0') str2.erase(0, 1);
Run Code Online (Sandbox Code Playgroud)