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

我正在做项目欧拉#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.为什么会这样?

@H_404_18@#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; }

解决方法

这里: @H_404_18@if(x.compare(y) == -1)

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

相关文章

/** C+⬑ * 默认成员函数 原来C++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录&lt;future&gt;future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...