计算全国组织机构代码的校验码(C++)

输入

全国组织机构代码的本体代码,由8位数字或大写拉丁字母组成。

输出

全国组织机构代码,本体代码后加连字符和校验码。

C++实现代码

#include 

int main()
{
	const int w[8] = { 3, 7, 9, 10, 5, 8, 4, 2 };
	int s = 0;
	bool bOK = true;
	char szID[11] = { 0 };

	std::cout << "Enter the master number of the organization ID: ";
	std::cin.getline(szID, sizeof(szID));
	for (int i = 0; i < 8; ++i) {
		char ch = szID[i];

		if ('0' <= ch && ch <= '9') {
			s += (ch - '0') * w[i];
		} else if ('A' <= ch && ch <= 'Z') {
			s += (ch - 'A' + 10) * w[i];
		} else {
			bOK = false;
			break;
		}
	}

	if (szID[8] != '\0') {
		bOK = false;
	}

	if (bOK) {
		int r = s % 11;

		szID[8] = '-';
		switch (r) {
		case 0:
			szID[9] = '0';
			break;
		case 1:
			szID[9] = 'X';
			break;
		default:
			szID[9] = 11 - r + '0';
			break;
		}

		szID[10] = 0;
		std::cout << std::endl << "The organization ID is: " << szID << std::endl;
		return 0;
	}

	std::cerr << std::endl
		<< "The master number is incorrect." << std::endl
		<< "It must be a combination of 8 digits (0~9) or uppercase alphbets (A~Z)." << std::endl;
	return 1;
}

参考

  • GB 11714-1997 全国组织机构代码编制规则

你可能感兴趣的:(C++)