编译器为Project Euler#22提供了不同的答案

pap*_*rbd 6 c++ cygwin g++ visual-studio

我正在做项目欧拉#22:

使用names.txt(右键单击和"保存链接/目标为..."),一个包含超过五千个名字的46K文本文件,首先按字母顺序排序.然后计算每个名称的字母值,将该值乘以列表中的字母位置以获得名称分数.

例如,当列表按字母顺序排序时,值为3 + 15 + 12 + 9 + 14 = 53的COLIN是列表中的第938个名称.因此,COLIN将获得938×53 = 49714的分数.

文件中所有名称分数的总和是多少?

用Cygwin的gcc-g ++编译器编译下面的代码,答案是871129635.但是使用Visual Studio 2008,答案是正确的871198282.为什么会这样?

#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;

bool strCmp(string x, string y) {
    if(x.compare(y) == -1)
        return true;
    else
        return false;
}

int getScore(string s) {
    int score = 0;
    for(unsigned int i = 0; i < s.length(); i++)
        score += (((int) s.at(i)) - 64);
    return score;
}

int getTotalScore(vector<string> names) {
    int total = 0;
    for(unsigned int i = 0; i < names.size(); i++)
        total += (getScore(names[i]) * (i+1));
    return total;
}

int main() {
    vector<string> names;
    ifstream namesFile("names.txt");

    char curChar;
    string curName = "";

    //get names from file
    if(namesFile.is_open()) {
        while(!namesFile.eof()) {
            curChar = namesFile.get();

            if(isalpha(curChar))
                curName.push_back(curChar);
            else {
                if(!curName.empty()) {//store finished name
                    names.push_back(curName);
                    curName.clear();
                }
            }
        }
    }
    namesFile.close();

    //alphabetize
    sort(names.begin(), names.end(), strCmp);

    //count up name scores
    cout << getTotalScore(names) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

int*_*jay 9

这里:

if(x.compare(y) == -1)
Run Code Online (Sandbox Code Playgroud)

您假设std::string::compare将返回-1一个小于结果,但它实际上可以返回任何负值.你可以通过使用来解决这个问题x.compare(y) < 0,但最好还是写一下x<y.实际上,您甚至不需要该strCmp函数,因为默认行为std::sort是使用比较元素operator<.