gpt4 book ai didi

Java - 根据用户的回答询问问题 x 次

转载 作者:行者123 更新时间:2023-12-01 11:00:05 24 4
gpt4 key购买 nike

我想根据答案问三个问题 x 次,然后我想根据给出的答案计算总成本。我想知道这种方式是否有效,如果有效,我如何计算总成本?

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("x ingredients?");
int amount = sc.nextInt();

for(int i = 1 ; i <= amount; i++) {
System.out.print("Nr " + i + ": How much do you have?\n");
int have = sc.nextInt();
System.out.print("Nr " + i + ": How much do you need?\n");
int need = sc.nextInt();
System.out.print("Nr " + i + ": How much does it cost?");
int cost = sc.nextInt();
if(i == amount) {
// calculate total cost
}
}
}

最佳答案

您需要跟踪循环外的总成本,否则它将超出范围。例如,在循环之前,初始化总成本:

int totalCost = 0; //you used sc.nextInt() so I assume no decimals

然后,在循环中,只需获取购买数量并乘以成本即可。

int toBuy = need - have;
//you do NOT need if (i == amount) because you will add to the cost whenever it's necessary, not just at the end of the loop
if (toBuy > 0){ //don't buy things you don't need
totalCost += toBuy * cost;
}

然后,在循环外打印总成本:

for (int i = 1; i <= amount; i++){
//...
}
System.out.println("Total cost of ingredients: " + totalCost);

关于Java - 根据用户的回答询问问题 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com