无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字
Without using loops, read the first 9 digits of an ISBN-10 as a string and calculate the 10th digit
我缺少章节中的东西;我已经读过它们的前后,但我认为我需要某种一般指导。
不允许使用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
相关文章:
- 递归形成字符串中所有数字字符的中间和?
- C++ 从 std::string 中删除所有非数字字符
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 如何使用 c++ 将数字字符转换为字符串
- 从字符数组中修剪非字母数字字符的功能
- 使用find_if和isalnum在字符串中找到字母数字字符
- 循环直到整数输入在所需范围内无法处理非数字字符输入
- 确保字符串只包含字母数字字符的更好方法
- 用C++计算文本文件中的字母数字字符
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 在读取C++行时过滤非字母数字字符
- C++ 如何从标准输入加载到最多 5 个字母数字字符的字符数组
- 如何知道小部件是否只接受数字字符
- 在 C++ STL 中,如何使用 regex_replace 从 std::string 中删除非数字字符
- i18n 去除非字母数字字符的友好方式
- 将字符数组拆分为字母数字字符和非字母数字字符
- 将多数字字符数转换为整数
- 在检测字符串是否包含数字字符时,这有什么问题
- 如何检测QString是否由所有数字字符组成