对于循环不打印我期望的。需要帮助

时间:2017-01-31 04:23:58

标签: c# if-statement for-loop console.writeline

int marsHeight = ml.getHeight() / 100 * 100; // measure by 100s despite height value
int chartHeight = (marsHeight >= 1000) ? marsHeight : 1000;
for (int i = 0; i <= (chartHeight / 100); i++)
{
    if (i == 0)
    {
        Console.WriteLine("{0}m: \t*", (marsHeight - (i * 100))); // in order to print in descending order: (height - (i * 100)
        continue;
    }
    Console.WriteLine("{0}m:", (marsHeight - (i * 100)));
}

如果marsHeight大于1000(我现在这样做),我希望我的程序打印出来:

[marsHeight]m: 
[marsHeight - 100]m:  
...  
1000m:   
900m:  
800m:   
...   
0m:  // this works perfectly!

目前,如果marsHeight小于1000(如990),程序将打印出来:

900m: *  
800m:  
...  
0m:  
-100m:

如果它不到1000米,我想要的是:

1000m:  
900m: *  
800m:  
...  
0m:  

我是编程新手。我的逻辑在哪里错了?

2 个答案:

答案 0 :(得分:2)

更改此

int chartHeight = (marsHeight >= 1000) ? marsHeight : 1000;

int chartHeight = (marsHeight <= 1000) ? marsHeight : 1000;
                              ^

并且如果您希望输出在两种情况下都相同,如果它更大或更小。您可以将其设为Not Equal to

int chartHeight = (marsHeight =! 1000) ? marsHeight : 1000;
                              ^^

答案 1 :(得分:1)

// First get the value.
int height = ml.getHeight();
// Now round to nearest even value.
int chartHeight = height / 100 * 100;
// Find initial value of cycle.
int forStart;
if (chartHeight > 1000)
    forStart = chartHeight;
else
    forStart = chartHeight < 0 ? 0 : 1000;
// Also you can simplify cycle.
for (int i = forStart; i >= 0; i -= 100)
    if(i==chartHeight)
        Console.WriteLine("{0}m:*", i);
    else
        Console.WriteLine("{0}m:", i);

输出将是:
如果身高990

1000m
900m*
...
0m

如果身高> 1000

1100m*
1000m
...
0m

如果身高540

1000m
...
500m*
...
0m