Home  >  Article  >  Database  >  有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一

有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一

WBOY
WBOYOriginal
2016-06-07 15:43:101173browse

import java.util.Scanner; //有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M。 需要选出若干个x,使这几个x的和与 M 最接近。 public class JieJin { public static void main(String args[]) { double[] l = new double[] { 1.1, 1

import java.util.Scanner;

//有N个正实数(注意是实数,大小升序排列) x1 , x2 ... xN,另有一个实数M。 需要选出若干个x,使这几个x的和与 M 最接近。

public class JieJin {

 public static void main(String args[]) {

  double[] l = new double[] { 1.1, 1.5, 1.6, 2.1, 2.2, 2.8, 3.8, 4.1 };

  Scanner cin = new Scanner(System.in);
  System.out.println("输入x:");
  int x = cin.nextInt();
  System.out.println("输入M:");
  double M = cin.nextDouble();
  double sum = 9999;

  int start = 0;

  for (int i = 0; i    if (sum(l, i, x, M)     sum = sum(l, i, x, M);
    start = i;
   }
   if (x + i >= l.length)
    break;
  }

  System.out.println(start);

 }

 private static double sum(double[] l, int i, int x, double M) {
  double sum = 0;
  for (int k = 0; k    sum = sum + chazhi(l[i], M);
   i++;
   if (i >= l.length)
    break;

  }
  return sum;
 }

 private static double chazhi(double a, double b) {
  if (a - b > 0)
   return a - b;
  else
   return b - a;
 }

}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn