我在章节中遗漏了一些东西,我已经前后阅读过了,但我想我需要一些一般性的指导。
不允许使用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;
}下面是修改过的代码,如果我成功了,我将将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;
}发布于 2018-04-23 10:17:29
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 == 1https://stackoverflow.com/questions/49978453
复制相似问题