我正在尝试根据用户输入来计算平均值。现在,我已经掌握了基础知识,但结果只得到了整数。我想要十进制数字,如5.5
欢迎任何解释!
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
@SupressLint("SetTextI18n")
public void onClick(View v) {
int grade[] = {Integer.parseInt(((EditText) findViewById(R.id.grade1)).getText().toString());
int weight[] = {Integer.parseInt(((EditText) findViewById(R.id.weight1)).getText().toString());
int weightTotal = weight[0];
int sum = grade[0] * weight[0]
int average = sum / weightTotal
averageView.setText(averageText + Integer.toString(average));
编辑:
我尝试了一个答案,并找到了解决问题的方法。
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
@SupressLint("SetTextI18n")
public void onClick(View v) {
double grade[] = {Double.parseDouble(((EditText) findViewById(R.id.grade1)).getText().toString());
double weight[] = {Double.parseDouble(((EditText) findViewById(R.id.weight1)).getText().toString());
double weightTotal = weight[0];
double sum = grade[0] * weight[0]
double average = sum / weightTotal
averageView.setText(averageText + " " + Double.toString(average));
答案 0 :(得分:0)
除法运算符/表示整数除法(如果存在整数) 在它的两边。如果一侧或两侧具有浮点数, 那么就意味着浮点除法整数除法的结果 始终是整数。整数除法确定一个数 整数进入另一个。整数除法后的余数为 不管它多大,都会掉落。
将变量平均值的类型更改为浮点型,然后将总和或权重之一转换为浮点型:
float average = (float)sum / weightTotal;
还将Integer.toString(average)
更改为Float.toString(average)
答案 1 :(得分:0)
您得到整数是因为您仅使用整数!!。
那是正常的,如果您希望平均值作为小数,则必须将其声明为Float
或Double
而不是int
。
请注意,即使您使用这种强制转换(Float.parseFloat ....),它也不会起作用,因为可变平均值只能包含整数。
答案 2 :(得分:0)
好,您可以这样做
final TextView averageView = findViewById(R.id.averageView);
final String averageText = getString(R.string.average);
final Button calculateButton = findViewById(R.id.calculateAverageButton);
calaculateButton.setOnClickListener(new View.onClickListener() {
@SupressLint("SetTextI18n")
public void onClick(View v) {
int grade = {Integer.parseInt(((EditText)
findViewById(R.id.grade1)).getText().toString());
int weight = {Integer.parseInt(((EditText)
findViewById(R.id.weight1)).getText().toString());
double sum = grade * weight
double average = sum / weight
averageView.setText(averageText +" "+ average);
答案 3 :(得分:0)
XsltTransformer trans = exp.load();
trans.setInitialContextNode(source);
FopFactory fopFactory = FopFactory.newInstance(fopxconfFile);
OutputStream outPdf = new BufferedOutputStream(new FileOutputStream(pdfFile));
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, outPdf);
trans.setDestination(new SAXDestination(fop.getDefaultHandler()));
trans.transform();
outPdf.close();
在从edittext获取数据以转换Integer时,也应使用try / catch。否则会崩溃