計算全國組織機構代碼的校驗碼(C++)

輸入

全國組織機構代碼的本體代碼,由8位數字或大寫拉丁字母組成。

輸出

全國組織機構代碼,本體代碼後加連字符和校驗碼。

C++實現代碼

#include <iostream>

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;
}

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章