I have this piece of code. When I run it, it returns 13, -13, and 0.
Isn t it supposed to return 1 if the str1
is greater than str2
and -1 if str1
is less than str2
.
我获得13、13和0。
#include <iostream>
#include <string>
#include <cstring>
int main() {
char str1[] = "Megadeth";
char str2[] = "Metallica";
// Should return -1 because "Megadeth" < "Metallica" lexicographically
int result = strcmp(str1, str2);
std::cout << "Comparing " << str1 << " and " << str2 << ": " << result << std::endl;
// Should return 1 because "Metallica" > "Megadeth" lexicographically
result = strcmp(str2, str1);
std::cout << "Comparing " << str2 << " and " << str1 << ": " << result << std::endl;
// Should return 0 because "Megadeth" = "Megadeth" lexicographically
result = strcmp(str1, str1);
std::cout << "Comparing " << str1 << " and " << str1 << ": " << result << std::endl;
return 0;
}
结果是:
Comparing Megadeth and Metallica: -13
Comparing Metallica and Megadeth: 13
Comparing Megadeth and Megadeth: 0
我刚刚在互联网上接受过辅导,他们说,这本应是回去的。 我不知道造成这种情况的原因。