常量的使用-1

常量的使用

namespace 示例2
{
    class Program
    {
        static void Main(string[] args)
        {
            //这段代码是想今天的星期数加1后输出,关注输出结果是否正确
            const int dayMax = 7; //每周的天数
            int today = 1; //今天的星期数
            Console.WriteLine("一周有几天");
            Console.WriteLine(dayMax);
            Console.WriteLine("明天是周");
            // dayMax = dayMax + 1; 常量只能在定义时修改,强制修改会报错,这样就保证了 dayMax不会被误操作
            today = today + 1;
            Console.WriteLine(today);
        }
    }
}

//由于程序员粗心 把"today=today+1" 写成 “dayMax=dayMax+1”
输出结果为8,与现实不符的情况,这种情况可以用常量来解决 // * 什么是常量? // * 常量:常量就是在程序运行过程中保持不变的值。
// * 例如以上示例代码 dayMax表示一周的天数就可以定义为常量。 // * 常量语法:const 数据类型常量名称 = 值
例如:publi const int datMax = 7 // * 常量命名规范: // *
具有一定的实际意义。最好以大写字母来命名,中间根据意义的连续性使用下划线做连接,最好注明注释。 // *
常量名称最好不要超过25个字符,否则可续性差。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43696086/article/details/86665103
今日推荐