魔法数字——没有明确含义的数字常量

admin

一、前言

今天写程序综合设计,了解到一个概念——魔法数字

我第一眼觉得这个概念好有意思,于是去搜集了资料,在此记录一下。

二、什么是魔法数字

"魔法数字"指的是在代码中直接出现的没有明确含义的数字常量,通常没有给出解释或者注释来说明其用途。这样的数字常量使得代码难以理解和维护,因为读者无法立即理解这些数字的含义和作用。

为了提高代码的可读性和可维护性,应该避免在代码中直接使用魔法数字,而是应该将其定义为有意义的常量或枚举值,使代码更易于理解。通过使用有意义的命名来替代魔法数字,可以使代码更具可读性,并且当需要修改这些值时也更容易进行维护。

三、消除魔法数字举例

原代码:

#include

int main() {

int scores[5] = {85, 90, 88, 92, 95};

int passingScore = 60;

int numPassing = 0;

for (int i = 0; i < 5; ++i) {

if (scores[i] >= passingScore) {

numPassing++;

}

}

std::cout << "Number of students passing: " << numPassing << std::endl;

return 0;

}

在上面的代码中,数字5是一个魔法数字,它表示了数组的长度。为了消除这个魔法数字,我们可以将其替换为一个常量,并在代码中使用该常量。

修改后的代码:

#include

const int NumStudents = 5;

int main() {

int scores[NumStudents] = {85, 90, 88, 92, 95};

int passingScore = 60;

int numPassing = 0;

for (int i = 0; i < NumStudents; ++i) {

if (scores[i] >= passingScore) {

numPassing++;

}

}

std::cout << "Number of students passing: " << numPassing << std::endl;

return 0;

}

通过将数字5替换为常量NumStudents,我们消除了魔法数字,提高了代码的可读性和维护性。

Copyright © 2088 中国战将网 - 顶级游戏活动平台 All Rights Reserved.
友情链接