【问题标题】:Without using loops, read the first 9 digits of an ISBN-10 as a string and calculate the 10th digit不使用循环,将 ISBN-10 的前 9 位读取为字符串并计算第 10 位
【发布时间】:2018-04-23 10:09:14
【问题描述】:

我在章节中遗漏了一些东西;我已经阅读了它们的正面和背面,但我认为我需要一些一般性的指导。

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

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

输入013601267,我不确定为什么我的输出是5,在我修改后的代码中的第10位校验和之后。该值应为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;
}

下面是修改后的代码,如果我成功了,我会将 ISBN 连接到 d10,但我将它们分开,因为我试图查看数学索引元素的值是什么。

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

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    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' -&gt; 1),您需要执行以下操作:

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

    【讨论】:

    • 谢谢哈米德!现在说得通了。现在要连接我所要做的就是添加“0”来获取字符并将其附加到字符串中。我做了 ISBN+= d10 + '0'。
    • @LuigiCampbell 取决于您的需要,如果您希望 1 成为 '1' 是的,+ '0' 是一种方法,但如果您希望 13601267 成为 "13601267",则不能简单地将'0' 添加到它。在这种情况下,您可以使用std::to_string。
    • 是的,将整数转换为字符串以连接两个元素。我只是想使用条件表达式将任何高于 9 的 mod 打印为 X。我最终在另一项任务中遇到了这个问题,但 std:: to_string 使它更容易。谢谢!
    猜你喜欢
    • 2017-01-21
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多