我正在尝试编写一个方法,它将减去多个数字而不是仅使用2个输入数字。
到目前为止,我有......
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
double difference = 0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
double valueTwo = in.nextInt();
difference = value - valueTwo;
}
System.out.println("Difference: " + difference);
}
这目前仅适用于2个输入,但我的最终目标是能够继续减去多个数字。
答案 0 :(得分:0)
而不是从value
继续减去,而是从difference
将difference = value - valueTwo;
更改为difference -= valueTwo
这相当于做((A - B) - C) - ...
,A是第一个输入,B是第二个输入,C是第三个输入......
答案 1 :(得分:0)
public void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double difference = in.nextDouble();
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
答案 2 :(得分:0)
这应该可以正常工作
#include <stdio.h>
int main()
{
int result=0, n,number,i;
printf("How many numbers you want to use?\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d", &number);
if(i ==0 ){
result=number;
}
else{
result -= number;
}
}
printf("Answer is= %d ", result);
return 0;
}
输出:
How many numbers you want to use?
4
55
34
1
3
Answer is= 17
答案 3 :(得分:-1)
此解决方案在第一次输入后不会挂起。它更加用户友好。
public static void getSub() {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the next number: ");
double difference = 0.0;
while(in.hasNextDouble()) {
System.out.print("Please enter the next number: ");
difference -= in.nextDouble();
}
System.out.println("Difference: " + difference);
}
答案 4 :(得分:-1)
为什么有两个变量?无论如何,以下更简单并正确提示:
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number: ");
double value = in.nextDouble();
while (true) {
in.nextLine(); // Silently discard rest of line
System.out.print("Please enter the next number, or . to stop: ");
if (! in.hasNextDouble())
break;
value -= in.nextDouble();
}
System.out.println("Difference: " + value);
测试
Please enter the number: 10
Please enter the next number, or . to stop: 1
Please enter the next number, or . to stop: 2
Please enter the next number, or . to stop: 3
Please enter the next number, or . to stop: .
Difference: 4.0