用Java中的方法按照比率从最低到最高对数组进行排序

huangapple go评论65阅读模式
英文:

Sorting arrays from lowest to highest numbers with ratios using methods in Java

问题

我正在编写一个程序,该程序接收配料的数量。程序如下:

import java.util.Scanner;

public class Restaurant {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int count = scan.nextInt();

    }
}
英文:

I am writing a program that takes in the number of ingredients. The prog

This is my code:

import java.util.Scanner;

public class Restaurant {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

		int count = scan.nextInt();

	
}

答案1

得分: 0

将这个sortCalories函数更改为以下方式。还需要将价格数组作为第二个参数传递,就像这样:sortCalories(calories, price, ingredientName);

public static void sortCalories(double[] calories, double[] price, String[] ingredientName) { 
    double temp;
    String temp1;

    for (int p = 0; p < calories.length; p++) {
        for (int j = p + 1; j < calories.length; j++) {
            if (calories[p] / price[p] > calories[j] / price[j]) {
                temp = calories[p];
                calories[p] = calories[j];
                calories[j] = temp;

                temp = price[p];
                price[p] = price[j];
                price[j] = temp;

                temp1 = ingredientName[p];
                ingredientName[p] = ingredientName[j];
                ingredientName[j] = temp1;
            }
        }
    }
}
英文:

Change this sortCalories function to the one below. Also you need to pass price array as second parameter like this sortCalories(calories,price, ingredientName);:

public static void sortCalories(double[] calories,double[] price, String[] ingredientName) { 
        double temp;
        String temp1;

        for (int p=0; p&lt;calories.length; p++) {
            for (int j=p+1; j&lt;calories.length; j++) {
                if(calories

/price

&gt;calories[j]/price[j]) { temp = calories

; calories

= calories[j]; calories[j] = temp; temp = price

; price

= price[j]; price[j] = temp; temp1 = ingredientName

; ingredientName

= ingredientName[j]; ingredientName[j] = temp1; } } } }

huangapple
  • 本文由 发表于 2020年8月24日 08:03:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63553163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定