【问题标题】:How to display output in single line如何在单行中显示输出
【发布时间】:2016-07-25 18:08:07
【问题描述】:

我的程序正在生成一个输出,但我期望的输出与生成的输出不同。 如果我发送 6 个输入数字,它应该比较数字并生成答案。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution 
{
    static void Main(String[] args) 
    {
        string[] tokens_a0 = Console.ReadLine().Split(' ');
        
        int a0 = Convert.ToInt32(tokens_a0[0]);
        int a1 = Convert.ToInt32(tokens_a0[1]);
        int a2 = Convert.ToInt32(tokens_a0[2]);
        
        string[] tokens_b0 = Console.ReadLine().Split(' ');
        
        int b0 = Convert.ToInt32(tokens_b0[0]);
        int b1 = Convert.ToInt32(tokens_b0[1]);
        int b2 = Convert.ToInt32(tokens_b0[2]);
        
        if (a0 > b0 || a0 < b0)
        {
            Console.WriteLine(1);
        }
        if (a1 > b1 || a1 < b1)
        {
            Console.WriteLine(1);
        }
        if (a2 > b2 || a2 < b2)
        {
            Console.WriteLine(1);
        }
    }
}

上面的代码正在生成以下输出:

1

1

我需要像这样显示输出:

1 1

如何更改代码以这种方式生成输出?

【问题讨论】:

  • 什么循环?!您是否尝试过阅读 Console.WriteLine 上的手册?您是否寻找过其他可能帮助您获得所需的输出方法?你有没有努力解决自己的问题?
  • 您的 if 语句正在检查一个数字是否大于或小于第二个数字...如果您可以缩短您的 if 语句(并使您的代码更易于阅读)将其替换为检查数字是否不相等。例如,if (a0 &gt; b0 || a0 &lt; b0) 语句可以更改为 if (a0 != b0)
  • " Console.WriteLine "将指定的数据,后跟当前行终止符,写入标准输出流。"换句话说,将指定的文本写入控制台中的新行。因此,输出不能与多个语句在同一行。单一的声明是唯一的方法。另外,正如@Sylverac 所提到的,您的代码效率低下。

标签: c# arrays console


【解决方案1】:

Console.WriteLine 就像名字所说的那样,写下你的消息,然后是一个新行。

如果你希望你的输出在同一行,你应该使用Console.Write:

if (a0 > b0 || a0 < b0)
{
   Console.Write(1 + " ");
}
if (a1 > b1 || a1 < b1)
{
    Console.Write(1 + " ");
}
if (a2 > b2 || a2 < b2)
{
    Console.Write(1 + " ");
}

【讨论】:

    【解决方案2】:

    其他答案是建议Console.Write,它们都是正确的。我只是想添加另一种方法来产生您正在寻找的结果,如果您觉得它有用的话,它可能允许对最终输出进行更多控制。

            string message = "";
            if (a0 > b0 || a0 < b0)
            {
                message += "1";
            }
            if (a1 > b1 || a1 < b1)
            {
                message += "1";
            }
            if (a2 > b2 || a2 < b2)
            {
                message += "1";
            }
            //make any further modifications to the result here, if needed
            Console.WriteLine(message);
    

    【讨论】:

      【解决方案3】:

      您想使用 Console.Write() 和空格字符而不是 Console.WriteLine()。

      if (a0 > b0 || a0 < b0)
         {
          Console.Write(1 + " ");
      }
      if (a1 > b1 || a1 < b1)
      {
          Console.Write(1 + " ");
      }
      if (a2 > b2 || a2 < b2)
      {
          Console.Write(1 + " ");
      }
      

      WriteLine() 将在输出文本后插入换行符。

      查看文档here 了解有关 Console.WriteLine() 的信息,查看文档here 了解有关 Console.Write() 的信息。

      【讨论】:

        猜你喜欢
        • 2017-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-16
        • 2022-07-22
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        相关资源
        最近更新 更多