2016-07-25 85 views
-5

我的程序正在生成一个输出,但我期待的输出不同于生成的输出。 如果我发送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

什么循环?!你有没有试过阅读Console.WriteLine手册?你有没有寻找其他输出方法,可以帮助你得到你想要的?你是否为解决自己的问题付出了一切努力? – Jakotheshadows

+0

您的'if'语句正在检查一个数字是否大于或小于第二个数字......如果您使用支票替换它,可以缩短您的if语句(并使代码更易于阅读)如果数字不相等。例如,if(a0> b0 || a0

+1

Console.WriteLine“将指定的数据以及当前行结束符写入标准输出流。”换句话说,将指定的文本写入控制台中的新行。因此,输出不能与多条语句在同一行。一个声明是唯一的方法。另外,正如@Sylverac所提到的,你的代码是低效的。 –

回答

4

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 + " "); 
} 
1

您想使用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()将在输出的文本后面插入一个换行符。

有关Console.Write()和有关Console.WriteLine()和here的信息,请参阅文档here

1

其他答案建议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);