C语言超市条形码识别代码:校验与洲别判定
这里提供一个简单的超市识别条形码的代码,需要用到字符串处理和条件语句。
#include <stdio.h>
#include <string.h>
int main() {
char barcode[13];
printf("请输入条形码:");
scanf("%s", barcode);
if (strlen(barcode) != 12) {
printf("条形码格式不正确\n");
return 0;
}
int sum = 0;
for (int i = 0; i < 12; i++) {
sum += (i % 2 == 0 ? 1 : 3) * (barcode[i] - '0');
}
int check_digit = (10 - (sum % 10)) % 10;
if (check_digit != barcode[12] - '0') {
printf("条形码校验失败\n");
return 0;
}
switch (barcode[0]) {
case '0':
case '1':
case '2':
printf("该商品来自亚洲\n");
break;
case '3':
case '4':
case '5':
printf("该商品来自欧洲\n");
break;
case '6':
case '7':
case '8':
case '9':
printf("该商品来自北美洲\n");
break;
default:
printf("条形码格式不正确\n");
break;
}
return 0;
}
代码思路:
- 读入条形码,如果长度不为12,输出错误提示。
- 对前12位数字进行校验,校验规则为:将奇数位数字乘以1,偶数位数字乘以3,将所有结果相加,得到一个数字。将这个数字除以10,取余数,再用10减去余数得到一个数字,就是校验位。如果校验位与条形码最后一位数字不同,输出错误提示。
- 根据条形码的第一位数字判断商品来自哪个洲,输出对应的提示。如果第一位数字不在0~9的范围内,输出错误提示。
原文地址: http://www.cveoy.top/t/topic/f10t 著作权归作者所有。请勿转载和采集!