【C#】Method()PracticalTest个人练习题

Q1.Create a program named Reverse3 whose Main() method declares three integers namedfirstlnt, middlelnt and lastInt. Assign values to the variables, display them, and then passthem to a method that accepts them as reference variables. The method places the firstvalue in the lastlnt, and places the last value in the firstlnt variable. In the Main() method,display the three variables again demonstrating that their positions have been reversed.

Q1。创建一个名为Reverse3的程序,它的Main()方法声明了三个整数firstlnt, middlent和lastInt。为变量赋值,显示它们,然后将它们传递给接受它们作为引用变量的方法。该方法将第一个值放在lastlnt变量中,并将最后一个值放在firstlnt变量中。在Main()方法中,再次显示这三个变量,以表明它们的位置已经颠倒。(知识点:reference parameter int firstInt -> ref int first middleInt->ref int second lastInt ->ref lastInt)

知识点reference 参数 reference parameter
R

everse(ref firstInt, ref middleInt, ref lastInt);  
  
static void Reverse(ref int first, ref int second, ref int third)  
{  

在上面的代码中:

Reverse方法被声明为接受三个ref参数:first、second和third。这意味着调用者必须提供三个变量的引用,而不是它们的值的副本。
在调用Reverse方法时,你使用了ref关键字来传递firstInt、middleInt和lastInt这三个变量。这告诉编译器,你想要传递这些变量的引用,而不是它们的当前值的副本。
在Reverse方法内部,你可以直接修改first、second和third的值,因为这些参数是通过引用传递的。任何对这些参数的修改都会反映到实际的变量firstInt、middleInt和lastInt上。
在方法内部,我提供了一个简单的示例来交换first和third的值,以及完成三个变量的轮换。具体的实现取决于你想要的“反转”逻辑是什么。

使用ref参数的好处是,它可以让你在方法内部修改调用者的变量,而不需要返回任何值。

这对于需要同时修改多个变量或执行复杂操作的情况非常有用。然而,你也需要小心,因为如果在方法内部不正确地处理ref参数,可能会导致调用者的变量被意外修改或产生不可预知的结果。

namespace Reverse3
{
  
    internal class Program
    {
        static void Main(string[] args)
        {
            int firstInt = 23;
            int middleInt = 30;
            int lastInt = 10;
            Console.WriteLine("The numbers are{0},{1},and{2}", firstInt, middleInt, lastInt);
            Reverse(ref firstInt, ref middleInt, ref lastInt);
            Console.WriteLine("The numbers are{0},{1},and{2}", firstInt, middleInt, lastInt);

            static void Reverse(ref int first,ref int second,ref int third) {
                int temp = first;
                first = third;
                third = temp;   
                 
                    }



        }
    }
}

Q2: Create a program named IntegerFacts whose Main() method declares an array of 10integers. Call a method to interactively fill the array with any number of values up to 10 oruntil sentinel value is entered. If an entry is not an integer, re-prompt the user. Call a secondmethod that accepts out parameters for the highest value in the array, lowest value in thearray, sum of the values in the array, and the arithmetic average. In the Main() methoddisplay all the statistics.

Q2创建一个名为IntegerFacts的程序,它的Main()方法声明了一个包含10个整数的数组。调用一个方法,以交互式方式用任意数量的值填充数组,最多10个,或者直到输入哨兵值。如果条目不是整数,则重新提示用户。调用第二个方法,该方法接受数组中最大值、数组中最小值、数组中值的总和和算术平均值的参数。在Main()方法中显示所有统计信息。

知识点:out 参数 out paramter

Statistics(num, numVals, out high, out low, out sum, out avg);//调用者在main方法中那个
static void Statistics(int[] array, int elements, out int high, out int low, out int sum, out int avg)

在这个示例中,Statistics 方法计算了整数数组中的最大值、最小值、总和以及平均值,并通过 out
参数将这些值返回给调用者。调用者可以这样使用这个方法: 在这个调用中,high, low, sum, 和 avg 变量在调用
Statistics 方法之前被声明,但没有被初始化。方法执行后,这些变量将被赋予相应的计算值,并可以在后续代码中使用。

在C#中,out 关键字用于方法参数,指示该参数是一个输出参数。这意味着该参数在方法内部将被赋予一个值,并且这个值会在方法返回时传递回调用者。与普通的输入参数(即没有使用 out 或 ref 的参数)不同,out 参数不要求在调用方法时为其提供一个初始值;相反,方法内部必须确保在返回之前为每个 out 参数分配一个值。

out 参数的工作原理如下:

1调用方法时:调用者不需要为 out 参数提供初始值。实际上,如果尝试在调用时为 out 参数提供一个值,编译器会生成一个错误。调用者只需要声明相应类型的变量,并在调用方法时将它们作为 out 参数传递。
**2方法内部:**方法必须为每个 out 参数分配一个值。如果方法在执行路径的任何地方没有为 out 参数分配值,则编译器会生成一个错误(通常是“未赋值的 out 参数”错误)。
**3方法返回时:**方法返回后,out 参数的值将被传递回调用者。调用者可以使用这些值进行进一步的处理或显示。

using System.Net.NetworkInformation;

namespace IntegerFacts
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] num = new int[10];
            int numVals = FillArray(num);
            int high;
            int low;
            int sum;
            int avg;
            Statistics(num, numVals, out high, out low, out sum, out avg);


            for (int i = 0; i < numVals; i++)
            {
                Console.WriteLine("Index {0} is {1}", i, num[i]);
                      
            } 
            Console.WriteLine();
             Console.WriteLine("The highest value is "+high);
            Console.WriteLine("The lowest value is " + low);
            Console.WriteLine("Sum is " + sum);
            Console.WriteLine("Average is " + avg);

            static int FillArray(int[] array)
            {
                const int QUIT = 999;
                int pos = 0;
                int entry = 0;
                while (pos<array.Length && entry != QUIT)
                {
                    Console.WriteLine("enter an integer or " + QUIT + "to exit ");
                    if (int.TryParse(Console.ReadLine(), out entry))
                    {
                        //if  true integer value
                        //before i update array i need to check QUIT
                        //doing conversion 2 values return flase return 0  
                        if (entry == QUIT)
                        {


                            array[pos] = entry;
                            pos = pos + 1;
                        }
                    }

                    else
                    {
                        Console.WriteLine("Invalid entry try again");

                    }

                }
                return pos;


            }

            static void Statistics(int[] array, int elements, out int high, out int low, out int sum, out int avg) {
                sum = 0;
                high = array[0];
                low = array[0];
                avg = 0;
                if (elements == 0) {
                    return;
                }
                for (int i = 0; i < elements; i++) {
                    sum = sum + array[i];
                    if (array[i] > high) {
                        high = array[i];
                    }
                    if (array[i] < low) {
                        low = array[i];
                    }
          }
                 if(elements!=0)
                avg = sum / elements;

            }
        }
    } 
}

Q3 Write a program named InputMethodDemo2 that eliminates the repetitive code in theInputMethod() in the InputProgramDemo program in Figure 8.5 in the Lecture. Rewritethe program so the InputMethod() contains only two statements:one = DataEntry(“first”); two = DataEntry(“'second");

  1. 编写一个名为InputMethodDemo2的程序,消除讲座中图8.5中的InputProgramDemo程序中的inputmethod()中的重复代码。重写程序,使InputMethod()只包含两条语句:一条= DataEntry(" first “);
    two = DataEntry(” 'second");
using System;  
  
class InputMethodDemo2  
{  
    // Simulated DataEntry method that takes a prompt and returns a string input  
    static string DataEntry(string prompt)  
    {  
        Console.Write(prompt + ": ");  
        return Console.ReadLine();  
    }  
  
    static void InputMethod()  
    {  
        // Only two statements as per the requirement  
        string one = DataEntry("Enter first value");  
        string two = DataEntry("Enter second value");  
  
        // Output the values for demonstration  
        Console.WriteLine("First value: " + one);  
        Console.WriteLine("Second value: " + two);  
    }  
  
    static void Main(string[] args)  
    {  
        InputMethod();  
    }  
}

Q4Write a program named Averages that includes a method that accepts any number of4.numeric parameters, displays them, and displays their average. Demonstrate that theprogram works correctly when passed one, two, or three numbers, or an array of numbers.

编写一个名为“平均数”的程序,其中包含一个接受任意数字“4”的方法。数值参数,显示它们,并显示它们的平均值。演示程序在传递一个、两个或三个数字或一个数字数组时正确工作。

知识点:params 参数
在C#中,params关键字允许你在方法的参数列表中定义一个可变数量的参数。这意味着你可以传递任意数量的参数给该方法,而不需要事先定义所有这些参数。params关键字必须用在数组类型的参数前,并且这个数组是方法参数列表中的最后一个参数。

params 参数的作用和效果:
1灵活性:params 使得 Average 方法可以处理任意数量的 double
值。你可以传递一个、两个、三个或更多 double 类型的参数,而不需要为每种情况编写不同的方法。
2.简化调用:当调用带有 params参数的方法时,你可以直接传递一组值,而不需要显式地将它们封装成数组。例如,Average(22.3, 22.3, 56.2) 直接传递了三个
double 值,而不是传递一个包含这三个值的数组。
3.数组处理:在方法内部,params参数被当作一个数组来处理。这意味着你可以使用数组的所有标准操作,比如遍历、索引和获取长度。
4.避免重载:使用 params可以减少或避免编写多个方法重载来处理不同数量的参数。这简化了代码库,使得维护和阅读代码更容易。

using System.Runtime.Intrinsics.X86;

namespace Params
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double[] array = { 1, 2, 3, 4, 5 };
            Average(3); //传递一个参数
            Average(15, 12); //传递两个参数
            Average(22.3, 22.3, 56.2); //传递三个参数
            DisplayMovie("The wizard of Oz", 101,2);
            DisplayMovie("Frozen");
        }
        static void DisplayMovie(string title, int value = 90, int category = 2)
        {
            Console.WriteLine("The movie is {0} has a running time of {1} and category is {2}",title,value,category);
        }
        static void Average(params double[] nums) {
            double total = 0;
            double avg = 0;
            foreach (double num in nums) { 
            total += num;
            }
            avg = total/nums.Length;
            Console.WriteLine("Average is"+avg);
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值