所以我在android studio中制作了一个简单的和应用程序
public void add(View view){
EditText editText1 = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
Float firstNumber = Float.valueOf(editText1.getText().toString());
Float secondNumber = Float.valueOf(editText2.getText().toString());
Float sum = firstNumber + secondNumber;
editText3.setText(sum.toString());
}
如何更改此值以便对两个数字之间的所有整数求和 例如,如果Text1 = 1且Text2 = 5则总和应为1 + 2 + 3 + 4 + 5
答案 0 :(得分:0)
这样的事情:
public void add(View view){
EditText editText1 = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
int firstNumber = Integer.valueOf(editText1.getText().toString());
int secondNumber = Integer.valueOf(editText2.getText().toString());
int sum = 0;
for(int i = firstNumber; i <= secondNumber; i++)
{
sum+=i;
}
editText3.setText("" + sum);
}
答案 1 :(得分:0)
您可以使用此方法查找总和
int sum(int smallest, int largest) {
int length = (largest - smallest + 1);
int sum = length * (smallest + largest) / 2;
return sum;
}
你可以这样打电话,
int firstNumber = Integer.parseInt(editText1.getText().toString());
int secondNumber = Integer.parseInt(editText2.getText().toString());
int sum = sum(firstNumber, secondNumber);
editText3.setText(sum.toString());
答案 2 :(得分:0)
试试这个
int firstNumber, secondNumber;
float ans = 0;
Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ans = 0;
firstNumber = Integer.parseInt(editText1.getText().toString());
secondNumber = Integer.parseInt(editText2.getText().toString());
for (; firstNumber <= secondNumber; firstNumber++) {
ans += firstNumber;
}
editText3.setText(ans + "");
}
});