所以我在我的 c++ 程序中收到一条奇怪的错误消息。目前使用视觉工作室(2012)。我有一个程序将一个数字的每隔一个数字相加,所以 1234567 就像 7+5+3+1=16,然后我取所有未相加的数字并将 em 乘以 2 并将它们相加。然后我将第一个 (16) 的结果相加,并将其添加到第二个的结果中。这是我的代码:
#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;
}