C#无需使用条件语句提取10-120区间数字个十百位值的方法
解决方案
完全可以通过算术运算直接提取各位数值,不需要任何if/switch分支判断,同时还能解决你现有代码中递归调用栈溢出、Random重复实例化导致随机值重复的问题:
核心实现逻辑
- 生成10~120区间偶数:直接用
rnd.Next(5, 61) * 2,生成的结果天然符合偶数、范围要求,无需额外奇偶判断 - 提取百位:
hundrds = digit / 100,因最大值为120,结果只会是0或1,完全符合需求 - 提取十位:
tens = (digit / 10) % 10,除以10取整后对10取余,自动适配两位数、三位数的场景 - 提取个位:
ones = digit % 10,直接对10取余即可得到个位数值
优化后完整代码
using System; namespace Digit_tests { class Program { static int digit; static int tens; static int ones; static int hundrds; // 全局只实例化一次Random,避免重复实例化导致随机值重复 static Random rnd = new Random(); public static void Main() { while(true) { // 直接生成10~120的偶数,无需额外判断 digit = rnd.Next(5, 61) * 2; // 算术运算直接提取各位,无任何分支判断 hundrds = digit / 100; tens = (digit / 10) % 10; ones = digit % 10; Console.WriteLine(digit + "\n" + hundrds + "-" + tens + "-" + ones); Console.ReadKey(); } } } }
内容的提问来源于stack exchange,提问作者UnnamedCat_
相关产品推荐
相关产品推荐

