如果连接,则使数字适合范围

问题描述 投票:-1回答:1

我有一个总变量我有250个范围中的250个我需要知道变量在哪个范围内,但是如果在15250的范围内进行链接,则必须做超过61个操作,还有另一种方法可以消除这种if的重复吗?谢谢您的帮助。例子

 public void ValidTravel(int Traveled)
 {
    int total = 15250
    int range = 250   

     if (Traveled>= 1 && Traveled<= 250)
        {                
           return 250;
        }

     if (Traveled>= 251 && Traveled<= 500)
        {                
           return 500;
        }

     if (Traveled>= 501 && Traveled<= 750)
        {                
           return 750;
        }

     if (Traveled>= 751 && Traveled<= 1000)
        {                
           return 1000;
        }

}
c# .net if-statement switch-statement case
1个回答
0
投票

您可以使用这些代码来检测范围并根据需要按X因子进行舍入处理

public int ValidTravel(int Traveled)
    {
        int total = 15250;
        int range = 250;
        double RetrunResult = 0;

        if (Traveled <= 0 || Traveled > total) // return error code -1 if Input value Traveled is not in range 1-15250
        { RetrunResult = -1; }
        else if (Traveled % range == 0) // use mod to cover value 250 , 500 , 750 , 1000....
        { RetrunResult = Traveled; } 
        else if (Traveled % 250 > 0)   // for those value that cant cover by mod , we will use divide value
        {
            double DivFactor = Traveled / 250;
            if (DivFactor >= 1)
            { RetrunResult = (Math.Ceiling(DivFactor) + 1 )* 250; } //  we know value greater then 250 so we will use ceiling function to force round up
            else if (DivFactor < 1)
            { RetrunResult = 250; }   // we know value is between 1-250 , so we will make RetrunResult = 250
        }


        return Convert.ToInt32(RetrunResult);


    }
© www.soinside.com 2019 - 2024. All rights reserved.