(2017-2)9位ISBN,求其校验位

问题描述:

给定一个9位数字的ISBN,求其校验位。ISBN格式为2-02-033598,校验位的计算方法如下:从左到右依次将各位数字乘10,9,8,……,2,求出其和S,作模运算得M=S mod 11。若11-M在1和9之间,校验位即为该数字;若11-M等于10,校验位为X;11-M等于11,校验位为0。输出添加校验位的ISBN,如2-02-033598-0。

样例输入:

输入1:

2-02-033598

输出1:

2-02-033598-0

输入2:

7-309-04547

输出2:

7-309-04547-5

思路:

字符数组存储,将数字依次取出存入Int型数组,进行计算即可

#include <cstdio>
#include <cstring>
char str[15];
int a[10];

int main(){
    scanf("%s", str);
    int count = 0;
    for(int i = 0; i < 11; i++){
        if(str[i] != '-'){
            a[count++] = str[i] - '0';
        }
    }
    int s = 0;
    int d = 10;
    for(int i = 0; i < 9; i++){
        s += a[i] * d;
        --d;
    }
    int m = s % 11;
    int t = 11 - m;
    if(t < 10){
        printf("%s-%d\n", str, t);
    }
    else if(t == 10){
        printf("%s-X\n", str);
    }
    else{
        printf("%s-0\n", str);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_35093872/article/details/87970178