无法弄清楚如何基于两个数字返回三个值之一

时间:2018-10-20 15:46:32

标签: c#

我正在用一个星号表示平均评级,并需要返回EmptyStar,HalfStar或FullStar的代码。 FullStar很简单,但我只能坚持。

currentCount 将是1到5,而 sum 是平均评分。

代码

string fa = string.Empty;

if (sum >= currentCount)
{
    fa = FullFaStar;
}
else if (???)
{
    fa = HalfFaStar;
}
else if (???)
{
    fa = EmptyFaStar;
}

2 个答案:

答案 0 :(得分:1)

也许这是您在寻找:

private static string FullFaStar = "full";
private static string HalfFaStar = "half";
private static string EmptyFaStar = "empty";

static void Main(string[] args)
{
    Console.WriteLine($"Value {0}");
    GetStarts(0);
    Console.WriteLine($"Value {0.5m}");
    GetStarts(0.5m);
    Console.WriteLine($"Value {0.8m}");
    GetStarts(0.8m);
    Console.WriteLine($"Value {2.4m}");
    GetStarts(2.4m);
    Console.WriteLine($"Value {3.2m}");
    GetStarts(3.2m);
    Console.WriteLine($"Value {4.5m}");
    GetStarts(4.5m);
    Console.WriteLine($"Value {5m}");
    GetStarts(5m);
    Console.ReadLine();
}

private static string GetStarts(decimal sum)
{
    string fa = string.Empty;
    for (int currentCount = 0; currentCount < 5; currentCount++)
    {

        if ((sum - currentCount) >= 1m)
        {
            fa = FullFaStar;
        }
        else if ((sum - currentCount) >= 0.5m)
        {
            fa = HalfFaStar;
        }
        else if (((sum - currentCount) < 0.5m))
        {
            fa = EmptyFaStar;
        }
        Console.WriteLine($"start {currentCount}: {fa}");

    }
    return fa;
}

结果:

Value 0
start 0: empty
start 1: empty
start 2: empty
start 3: empty
start 4: empty
Value 0,5
start 0: half
start 1: empty
start 2: empty
start 3: empty
start 4: empty
Value 0,8
start 0: half
start 1: empty
start 2: empty
start 3: empty
start 4: empty
Value 2,4
start 0: full
start 1: full
start 2: empty
start 3: empty
start 4: empty
Value 3,2
start 0: full
start 1: full
start 2: full
start 3: empty
start 4: empty
Value 4,5
start 0: full
start 1: full
start 2: full
start 3: full
start 4: half
Value 5
start 0: full
start 1: full
start 2: full
start 3: full
start 4: full

答案 1 :(得分:0)

我必须添加一些“自定义”修复程序,但是它可以按预期运行。

代码

string fa = EmptyFaStar;
double tmp = (sum - currentCount).Decimals();

if (!tmp.IsPositive())
{
    tmp = tmp * -1;
}

if (sum >= currentCount)
{
    fa = FullFaStar;
}
else if (tmp >= 0.5)
{
    fa = HalfFaStar;
}
else if (tmp < 0.5)
{
    fa = EmptyFaStar;
}

if (last.Equals(HalfFaStar) && fa.Equals(HalfFaStar))
{
    fa = EmptyFaStar;
}
else if (last.Equals(EmptyFaStar) && !fa.Equals(EmptyFaStar))
{
    fa = EmptyFaStar;
}

last = fa;