从包括空格而不是换行的一行中读取字符

时间:2018-11-11 16:45:47

标签: c# arrays loops

在C#中,我正在尝试解决一个问题: 编写一个程序,检查奇数元素的乘积是否等于偶数元素的乘积。

唯一剩下的是:  在第二行,您将收到由空格分隔的N个数字。 我无法正常工作。我已经尝试过Split,但是它一直在中断。有人可以帮忙吗?

示例:

输入
5 2 1 1 6 3
输出

是6

#!/usr/bin/python3

import subprocess
import time
import logging

logging.basicConfig(filename='wifi_check.log', filemode='w', format='%(name)s - %(levelname)s 
    - %(message)s', level=logging.DEBUG)

logging.info("Checking for Wifi")

for i in range(20):

    try:
        iwconfig_output = subprocess.check_output(['iwconfig']).decode('utf-8')
    except Exception as err:
        logging.error(str(i) + str(err))
    else:
        logging.debug(str(i) + iwconfig_output)
        if "ESSID" in iwconfig_output:
            logging.info(str(i) + "Wifi active")

    time.sleep(10)

2 个答案:

答案 0 :(得分:1)

  

从控制台输入中读取并保存到string数组中,然后将每个数组元素转换为long并应用Odd Even逻辑,如下所示:

static void Main(string[] args)
    {
        string input = Console.ReadLine();
        string[] inputArray = input.Split(' ');

        long element;
        long odd = 1;
        long even = 1;
        foreach (var i in inputArray)
        {
            element = long.Parse(i);
            if (element % 2 == 0)
            {
                even *= element;
            }
            else
            {
                odd *= element;
            }
        }

        Console.WriteLine("\nOdd product = " + odd + ", Even product = " + even);

        if (odd == even)
        {
            Console.WriteLine("ODD == EVEN \n");

            Console.WriteLine("Yes" + " " + odd);
        }
        else
        {
            Console.WriteLine("ODD != EVEN \n");

            Console.WriteLine("No" + " " + odd + " " + even);
        }
        Console.ReadKey();

    }

答案 1 :(得分:0)

long[] nums = input.Split(' ').Select(x => long.Parse(x))..ToArray(); //split numbers by space and cast them as int
int oddProduct = 1, evenProduct = 1; // initial values

foreach(long x in nums.Where(a => a%2 == 1))
    oddProduct *= x;    // multiply odd ones

foreach(long x in nums.Where(a => a%2 == 0))
    evenProduct *= x;   // multiply even ones