无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字

Without using loops, read the first 9 digits of an ISBN-10 as a string and calculate the 10th digit

本文关键字:数字 字符 读取 字符串 串并 10位 计算 9位 循环 的前 ISBN-10      更新时间:2023-10-16

我缺少章节中的东西;我已经读过它们的前后,但我认为我需要某种一般指导。

不允许使用loops,我已经阅读了Java和Python示例。

我应该修改我的第一个(顶部(代码以使用getline使用字符串输入,然后计算ISBN-10的最后一个数字。

使用013601267的输入,我不确定为什么在修改后的代码中获得第10位数字后我的输出是5。该值应为 1

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
  cout
  << "Enter the first nine digits as integerss of an ISBN.."
  <<endl;
  int d1, d2, d3, d4, d5, d6, d7, d8, d9;
  int d10;
  cin
  >> d1
  >> d2
  >> d3
  >> d4
  >> d5
  >> d6
  >> d7
  >> d8
  >> d9;
  d10 = ( d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9 ) % 11;
  if ( d10 > 9)
  {
    cout
    << "d10: "
    << d10
    << endl
    <<"The corresponding ISBN-10 is... "
    << d1
    << d2
    << d3
    << d4
    << d5
    << d6
    << d7
    << d8
    << d9
    << 'X'
    << endl;
  }
  else
  {
    cout
    << "d10: "
    << d10
    << endl
    <<"The corresponding ISBN-10 is... "
    << d1
    << d2
    << d3
    << d4
    << d5
    << d6
    << d7
    << d8
    << d9
    << d10
    <<endl;
  }
  return 0;
}

以下是修改的代码,如果我成功,我将与D10进行串联ISBN,但是当我试图查看数学索引元素的值时,我将它们分开了。

#include <iostream>
#include <string>
#include <cmath>

using namespace std;
int main()
{
  cout
  << "Enter the first nine digits of an ISBN-10..."
  << endl;
  string ISBN;
  getline(cin, ISBN, 'n');
  int d10 = ( ISBN[0] * 1 + ISBN[1] * 2 + ISBN[2] * 3 + ISBN[3] * 4 + ISBN[4] * 5 + ISBN[5] * 6 + ISBN[6] * 7 + ISBN[7] * 8 + ISBN[8] * 9 ) % 11;

  cout
  << d10
  << endl
  << ISBN
  << endl;
  return 0;
}

std::string字符不是整数的数组。在C 中,'1'不等于1

您正在做的是添加字符ASCII代码。您需要做的是更改d10这样的计算:

int d10 = ( (ISBN[0] - '0') * 1 + (ISBN[1] - '0') * 2 + (ISBN[2] - '0') * 3 + (ISBN[3] - '0') * 4 + (ISBN[4] - '0') * 5
 + (ISBN[5] - '0') * 6 + (ISBN[6] - '0') * 7 + (ISBN[7] - '0') * 8 + (ISBN[8] - '0') * 9 ) % 11;

要将字符转换为实际整数值(我的意思是'1' -> 1(,您需要做类似的事情:

char a = '1';
int ia = a - '0'; //ia == 1