문제

I'm attempting to write a program in which the user enters an ISBN then checks the entry for accuracy. The ISBN is 0201702894. The check digit (the 4) is calculated from the other 9 digits as follows – the (sum of each (digit times its position)) mod 11. Ex: (0*1 + 2*2 + 0*3 + 1*4 + 7*5 + 0*6 + 2*7 + 8*8 + 9*9)%11 = (0+4+0+4+35+0+14+64+81)%11 = 4 (202/11 = 18 remainder 4) The check digit can detect when an ISBN is entered or copied incorrectly.

Each time I enter values, I always have the "ISBN is not correct" output. Something is wrong with my logic.

1.  Correct Value: 0201702894

2.  Incorrect value: 0201702984

Code:

#include <iostream>

using namespace std;

int totalNumbersCheck=0;

int main()
{
int isbnArray[10];      //array to store the ISBN numbers
int ISBN=0;             //inputted ISBN number

//user input

cout<<"Please enter the ISBN number: ";
cin>>ISBN;

//ISBN storage

isbnArray[ISBN];

//ISBN calculation

for(int i=0;i<10;i++)
{
    totalNumbersCheck=isbnArray[i]*(i+1);
}

//remove last element from array

    totalNumbersCheck-=isbnArray[10];

//check if remainder equals last element and output correct response

    if(totalNumbersCheck%11==isbnArray[10])
    {
        cout<<"\nThe ISBN is correct.";
    }
    else
        cout<<"\nThe ISBN is not correct.";

    cin.get();
    cin.get();

return 0;
  }
도움이 되었습니까?

해결책 2

Read the isbn into a std::string variable, then loop through the characters in the string, convert each to a digit, and apply your algorithm.

const isbn_digits = 10;
std::string isbn;
std::cin >> isbn;
assert(isbn.size() == isbn_digits);
int sum = 0;
for (int pos = 0; pos < isbn_digits - 1; ++pos)
    sum += (pos + 1) * (isbn[pos] - '0');
if (sum % 11 != isbn[isbn_digits - 1] - '0')
    // error

다른 팁

  isbnArray[ISBN];

is wrong, since ISBN is a 11 digit number which may start from 0. You would like to instead store each digit of the ISBN into the array isbnArray. Assume the input number is 1233445, this index is certainly out of your range of isbnArray[9].

Meanwhile, the loop for computing the result may should look like this:

 for(int i=0;i<10;i++)
 {
    totalNumbersCheck +=isbnArray[i]*(i+1);
 }

 if(totalNumbersCheck%11==isbnArray[9])
                   ///^^index out of bound again if you access isbnArray[9]

You know that ISBN is 11 digits, so you should at least use an array of length 11 not 9.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top