,所以我让我的C++程序一个奇怪的错误消息。目前正在使用视觉工作室(2012)。我有一个程序添加了一个数字的其他数字,所以1234567就像7 + 5 + 3 + 1 = 16,然后我把所有非增加的数字和em乘以2并加上em。然后我把第一个(16)的结果加起来并加到第二个结果中。这里是我的代码:随机1无法解析的外部错误
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;
int sumAltDigits(int);
int sumNonDigits(int);
int main() {
long cardNumber; //cardNumber must stay as 'long'. Teacher says so.
string in;
stringstream ss;
int total;
cout << "Please enter a chain of integers: ";
getline(cin, in);
ss.clear(); ss.str(in);
while (!(ss >> cardNumber) || (cardNumber < 1)); {
cout << sumAltDigits(cardNumber) << endl;
//get answer
total = sumAltDigits(cardNumber) + sumNonDigits(cardNumber); //this line causes me an error, sumNonDigits(cardNumber)
}
system("pause");
}
// adds every other digit, starting from the right
int sumAltDigits(int cardNumber)
{
if (cardNumber < 10)
return cardNumber;
return (cardNumber % 10) + sumAltDigits(cardNumber/100);
}
// adds digits that were not included in previous step, multiply them by 2, then add all digits in those numbers
int sumNonDigits(string cardNumber) // I think the error is also being caused by string cardNumber, but if i try to change that, it screws up this function.
{
int checkSum = 0;
int i;
for (i = cardNumber.length() - 2; i >= 0; i -= 2) {
int val = ((cardNumber[i] - '0') * 2);
while (val > 0) {
checkSum += (val % 10);
val /= 10;
cout << checkSum << endl;
}
}
return checkSum;
}
哦该死!我不能相信我错过了这一点。呃,当我改变int sumNonDigits(int)到(字符串)时,它说我不能将long cardNumber转换为一个字符串cardNumber – 2013-02-25 02:03:11
@Averagekid:不,你需要用'std:'调用'sumNonDigits() :string'。也许'in'就足够了? – Johnsyweb 2013-02-25 02:09:30
恩,对不起,我对字符串不太了解,还挺新的C++。你什么意思? – 2013-02-25 02:19:25