调用方法计算数组的和,最大值,最小值

本文提供了一个使用C#计算数组中元素的和、最大值和最小值的示例程序。通过一个具体的方法实现,展示了如何遍历数组并进行数值运算。
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication7
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //调用方法计算数组的和,最大值,最小值
14             int[] array = { 5, 2, 1, 6, 9, 11, 18, 3 };
15             int max, min, sum;
16             sum = compute(array,out max,out min);//该行的max,min,sum和上一行的为同一变量,但与调用方法中的同名变量不同,调用方法的变量只是返回值给本行相同名变量
17             Console.WriteLine("数组的和为:{0}    最大值为{1} 最小值为{2}",sum,max,min);
18             Console.ReadKey();
19         }
20 
21         static int compute(int[] numbers, out int max, out int min)
22         {
23             int sum = 0;
24             max = numbers[0];
25             min = numbers[0];
26             for (int i = 0; i < numbers.Length; i++)
27             {
28                 sum += numbers[i];
29                 if (numbers[i] > max)
30                 {
31                     max = numbers[i];
32                 }
33                 if (numbers[i] < min)
34                 {
35                     min = numbers[i];
36                 }
37             }
38             return sum;
39         }
40         
41     }
42 }

 

转载于:https://www.cnblogs.com/start-from-scratch/p/5056934.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值