c#:当result为0时,在命令行中不显示result

本文关键字:result 命令行 显示 0时 | 更新日期: 2023-09-27 18:11:50

我在学校有一个c#的任务。我有这个问题与以下代码(示例)

static void Main()
{
    do
    {
        Console.Write("Amount of centimeters?: ");
        double centimeters = double.Parse(Console.ReadLine());
        double meters = centimeters / 100;
        Console.WriteLine($"Amount of meters: {meters}");
        int wholeMeters = (int)meters;
        Console.WriteLine($"Amount of whole meters: {wholeMeters}");
    }while (true);
}
<标题>结果:
  • 厘米数?350:
  • 仪表数量:3,5
  • 整米数量:3

  • 厘米数?: 50
  • 仪表数量:0,5
  • 整米数量:0

如果"整米的数量"的结果为0,我不想在控制台中显示"整米的数量:"这行。

:

  • 厘米数?: 50
  • 仪表数量:0,5

我怎么能做到这一点,只使用'System'命名空间?

c#:当result为0时,在命令行中不显示result

在不久的将来你肯定会学到控制结构。只需检查wholeMeters字段的值并对结果

进行操作
if(wholeMeters != 0)
   Console.WriteLine($"Amount of whole meters: {wholeMeters}");

实际上这是我的练习,我通过一步一步地再次执行代码找到了结果(花了我1天时间!!):))

static void Main()
{
    do
    {
        Console.Write("Timespan in seconds?: ");
        int timeInSeconds;
        if (int.TryParse(Console.ReadLine(), out timeInSeconds))
        {
            Console.WriteLine("This is:");
            double amountOfDays = timeInSeconds / 86400;
            if (amountOfDays != 0)
                Console.WriteLine($"- {(int)amountOfDays} days");
            double amountOfHours = timeInSeconds / 3600 - ((int)amountOfDays * 24);
            if (amountOfHours != 0)
                Console.WriteLine($"- {(int)amountOfHours} hours");
            double amountOfMinuts = timeInSeconds / 60 - ((int)amountOfHours * 60) - ((int)amountOfDays * 24 * 60);
            if (amountOfMinuts != 0)
                Console.WriteLine($"- {(int)amountOfMinuts} minuts");
            double amountOfSeconds = timeInSeconds - ((int)amountOfMinuts * 60) - ((int)amountOfHours * 60 * 60) - ((int)amountOfDays * 24 * 60 * 60);
            if (amountOfSeconds != 0)
                Console.WriteLine($"- {(int)amountOfSeconds} seconds");
        }
        else
        {
            Console.WriteLine("Please enter a positive integer!");
        }
    } while (true);
}

}

  • 以秒为单位的时间跨度?: 34567788
    • 这是:
      • 2小时/gh>
      • 9分钟
      • 48秒
  • 以秒为单位的时间跨度?: 34567
    • 这是:
      • 9小时
      • 36分钟
      • 7秒时间跨度以秒为单位?: 2345这是:
      • 39分钟
      • 5秒
  • 以秒为单位的时间跨度?: 45
    • 这是:
      • 45秒
  • 以秒为单位的时间跨度?: 20
    • 请输入正整数!

我知道必须使用if语句,但是我在代码开头声明了(双精度)变量,而不是在每次计算之前声明。

无论如何,谢谢你的帮助!