gpt4 book ai didi

c++ - 编译器为 Project Euler #22 给出了不同的答案

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:34 25 4
gpt4 key购买 nike

我在做欧拉计划#22:

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

用 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;
}

最佳答案

这里:

if(x.compare(y) == -1)

您假设 std::string::compare将返回 -1对于小于结果,但实际上它可以返回任何负值。您可以使用 x.compare(y) < 0 解决此问题, 但最好只写 x<y .事实上,您甚至不需要 strCmp功能,因为 std::sort 的默认行为是使用 operator< 比较元素.

关于c++ - 编译器为 Project Euler #22 给出了不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6682433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com