试图从数组计算 [英] trying to calculate from an array

查看:58
本文介绍了试图从数组计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,这是我的问题。我必须创建一个程序,用户可以输入一个数字,它将显示该数字乘以数组中的数字后的数字。它必须是它自己的方法并由Main调用。我得到一个结果,但它不应该接近结果。我很难过。

Guys, here's my problem. I have to create a program that the user can enter a number and it will show what that number is after being multiplied by the numbers in the array. It has to be it's own method and be called by the Main. I get a result but it isn't close to the result it should be. I'm stumped.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplication
{
    class Program
    {
        static void Main(string[] args)
        {
            
            

            Console.Write("Please enter a number ");
            
            MultiplicationTable();
           

            
          }
        private static void MultiplicationTable()
        {
            int answer;
            int number;
            
            int[] times = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            
            number = Console.Read();
            number = Convert.ToInt32(number);
            answer = number *  times[8];
            
            Console.Write(" The product is " + answer);
            
          

            
            }
    }
}

推荐答案

要做的第一件事是读取main方法中的数字,并将其作为参数传递给方法:

The first thing to do is read the number in the main method, and pass it to the method as a parameter:
string inp = Console.ReadLine();
int x;
if (int.TryParse(inp, out x))
    {
    MultiplicationTable(x);
    }



然后你可以使用一个简单的循环进行乘法运算:


You can then do the multiplication, using a simple loop:

private static int[] timesTable = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

private static void MultiplicationTable(int x)
    {
    foreach (int times in timesTable)
        {
        Console.WriteLine("{0} x {1} = {2}", x, times, x * times);
        }
    }


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int number;
            Console.Write("Please enter a number: ");
            var x = Console.ReadLine();
            number = Convert.ToInt32(x);
            MultiplicationTable(number);
        }

        private static void MultiplicationTable(int num)
        {
            int[] times = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int answer;
            foreach(int tnum in times)
            {
                 answer = num *  tnum;
                 Console.Write("The product of " + num + " x " + tnum + " = " + answer);
            }
        }
    }
}



与解决方案1相同,只是显示不同


Same as Solution 1, just shown differently


这篇关于试图从数组计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆