求平衡点问题的C#代码(python面试题转换)

Code:
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5.   
  6. namespace KingAndPrisoner   
  7. {   
  8.     class pinghengdian   
  9.     {   
  10.         /// <summary>   
  11.         /// </summary>   
  12.         /// <param name="args"></param>   
  13.         static void Main(string[] args)   
  14.         {   
  15.             int[] num = { 1, 3, 5, 7, 8, 25, 4, 20 };//定义数组   
  16.             int fore = 0;//求平衡点之前的数之和              
  17.             int total = sum(num);//求数组之和   
  18.             foreach (int i in num)//遍历数组   
  19.             {                  
  20.                if (fore < (total-i)/2)//判断遍历至数据组中某一个数时,该数之前的和是否为数组整体之和减去该数除2,小于,说明平衡点在该数之后   
  21.                 {   
  22.                     fore += i;                     
  23.                 }   
  24.                else//否则,该数为下一位即为平衡点   
  25.                {   
  26.                   break ;   
  27.                }   
  28.             }   
  29.             foreach (int j in num)//遍历数组   
  30.             {   
  31.                 if (fore == (total - j) / 2)//判断遍历至数据组中某一个数时,该数是否为平衡点,是,输出   
  32.                 {   
  33.                     Console.WriteLine(j);   
  34.                 } 
  35.                  else
  36.                    
  37.                 {
  38.                       Console.WriteLine("不存在");   
  39.                       break;
  40.                 }  
  41.             }   
  42.               
  43.         }   
  44.         //求数组之和   
  45.         public static int sum(int[] num)   
  46.         {   
  47.             int sum = 0;   
  48.             for (int i = 0; i < num.Length; i++)   
  49.             {   
  50.                 sum += num[i];   
  51.             }   
  52.             return sum;   
  53.         }   
  54.   
  55.     }   
  56. }   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值