gpt4 book ai didi

java - 使用小于零的数字进行计算

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

如果这个问题确实很明显,但我已经尝试了一切,请原谅。

我正在尝试制作一个计算数字百分比的计算器。

但是当我使用此代码时,它一直输出 0:

import java.io.*;

class pCalc {
public static void main(String args[])
{
InputStreamReader istream = new InputStreamReader(System.in) ;
BufferedReader bufRead = new BufferedReader(istream) ;

System.out.println("Hello...");

try {
System.out.println("Please Enter In The Percentage You Want To Find (e.g 25): ");
String rpercent = bufRead.readLine();

System.out.println("Please Enter In The Number You Wish To Find The Percentage Of (e.g 200): ");
String rnumber = bufRead.readLine();


int repercent = Integer.parseInt(rpercent);
int number = Integer.parseInt(rnumber);
int percent = repercent / 100;

int awnswer = number * percent ;

System.out.println("Percent is: " + percent);
System.out.println("Awnswer is: " + awnswer);
}
catch (IOException err) {
System.out.println("Error reading line");
}
catch(NumberFormatException err) {
System.out.println("Error Converting Number");
}
}
}

最佳答案

你的问题出在这里:

       int repercent = Integer.parseInt(rpercent);
int number = Integer.parseInt(rnumber);
int percent = repercent / 100;

整数除法的结果最终将是一个整数,因此,例如,如果计算结果为 0.2,它将更改为 0

这样做应该可以解决这个问题:

   double repercent = Double.parseDouble(rpercent);
double number = Double.parseDouble(rnumber);
double percent = repercent / 100.0;

关于java - 使用小于零的数字进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381648/

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