gpt4 book ai didi

java - 我试图找出脂肪中卡路里的百分比,但我的输出从来都不正确

转载 作者:行者123 更新时间:2023-12-01 17:34:10 25 4
gpt4 key购买 nike

这是我的代码

import java.util.Scanner;
import java.text.DecimalFormat;

public class Calories
{
public static void main (String[] args)
{

int fat; //Grams of fat
int fcal; //Calories from fat
int total; //Number of Calories
long result; //Percent of calories from fat

System.out.println("This program finds the percent of calories from fat");

//Here the user inputs the numbers
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter the total grams of fat " );

fat = keyboard.nextInt();
fcal = fat * 9;
System.out.print("Enter the total number of calories " );

total = keyboard.nextInt();
result = fcal / total * 100;

if(result <= 30)
{
System.out.println("Food is low in fat!");
}
DecimalFormat formatter = new DecimalFormat("#0");
System.out.println("Calories from fat : " + formatter.format(result) + "%");
}
}

无论我输入什么,我的输出总是为零。谁能告诉我我在这里做错了什么?我不确定是 DecimalFormat、数据类型还是 Keyboard.nextInt();是我问题的一部分,我已经多次检查过它并询问了另一个人,他说代码对他们来说运行良好。

最佳答案

您的fcaltotal变量都是整数,因此您正在执行整数除法。随时fcal < total ,您将始终得到 0 作为答案。

在进行除法运算时,您需要将其转换为 double 。

result 开始,这也不太有效。声明为long所以会损失精度。更改 result 的数据类型否则将结果转换回 long .

关于java - 我试图找出脂肪中卡路里的百分比,但我的输出从来都不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8057884/

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