gpt4 book ai didi

java - 在java中执行除法的正确方法

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

好吧,我已经为此搜索了很多次,但回来后却摸不着头脑...我已经习惯了 php,对 java 还很陌生,所以请耐心等待...

我正在构建一个应用程序,它可以执行一些基本数学操作(个人应用程序,而不是营销它),我将每天使用它。该应用程序安装良好并运行,但当我点击计算按钮时,我得到 0 作为答案。我做错了什么?

float val1 = Integer.parseInt(fat.getText().toString()) *1;
float vals1 = (int) 3.89;
float val2 = Integer.parseInt(carbs.getText().toString()) *1;
float vals2 = (int) 9.17;
float val3 = Integer.parseInt(fiber.getText().toString()) *1;
float vals3 = (int) 12.49;
float val4= Integer.parseInt(protein.getText().toString()) *1;
float vals4 = (int) 10.94;
float answer = (float) (((val4 / vals4) + (val2 / vals2) + (val1 / vals1)) - (val3 / vals3));
Integer answerf = (int) answer;
points.setText(answerf.toString());

编辑:根据要求的预期值(用于测试运行)

val1 = 7
val2 = 26
val3 = 2
val4 = 5

预期结果是 5

最佳答案

检查您的EditTexts是否包含有效的数字,然后执行以下操作:在此示例中,我假设 EditText 包含值“10”。

    float val1 = Integer.parseInt("10") *1;
float vals1 = 3.89f;
float val2 = Integer.parseInt("10") *1;
float vals2 = 9.17f;
float val3 = Integer.parseInt("10") *1;
float vals3 = 12.49f;
float val4= Integer.parseInt("10") *1;
float vals4 = 10.94f;
float answer = (float) (((val4 / vals4) + (val2 / vals2) + (val1 / vals1)) - (val3 / vals3));

System.out.println("Result: " + answer);

这里的结果是:3.7746425

Furthermore, it does not make any sense to cast your double values to int to be able to assign them to float.

关于java - 在java中执行除法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18519981/

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