计算总金额

时间:2016-10-22 00:52:08

标签: java

当试图跑时,我得到了错误的答案。我的课程有什么问题? 只有discount_amount无法获得总金额才能得到答案。

    Scanner input = new Scanner(System.in);

    double dicount_amount = 0;
    double discount1 = 0;
    double total = 0;

    System.out.println("Enter the cost of the software: ");
    double cost = input.nextDouble();

    System.out.println(" Enter the quantity sold: ");
    int quantity = input.nextInt();
    if (cost > 0 && quantity > 0){


    if(quantity >= 10 && quantity >=19){
         discount1 = 20/100;
    }
    else if(quantity >= 20 && quantity >=49){
        discount1 = 30/100;
    }   
    else if(quantity >= 50 && quantity >=99){
         discount1 = 40/100;
    }
    else if(quantity <=100){
        discount1 = 50/100;
    }

    }
    else {

        System.out.println( " please enter valid input ");
    }

    double total1 = cost * quantity;
    dicount_amount = total1 * discount1; 
    total=  total1 - dicount_amount;

    System.out.println("Total Cost: " + total);

}

2 个答案:

答案 0 :(得分:1)

您可以做的最简单的事情就是不要划分endl,而是可以直接设置值discount1 = 20/100;

另外你应该检查你的if语句

示例:

discount1 = 0.2;

等于

if(quantity >= 10 && quantity >=19)

我想你想检查数量是否介于两者之间。所以你应该使用

if(quantity >=19)

答案 1 :(得分:1)

猜猜你的错是什么?你把int除以int,你得到的是双重结果。将该分区加倍或做20.0/100。此外,我假设你想要在10到19之间给予折扣。你一直在做什么没有意义,因为每次你运行你的程序时它都不会落入else if()声明,因为你正在if语句中设置quantity>=19

我在您的代码中进行了一些更改:

Scanner input = new Scanner(System.in);

double dicount_amount = 0;
double discount1 = 0;
double total = 0;

System.out.println("Enter the cost of the software: ");
double cost = input.nextDouble();

System.out.println(" Enter the quantity sold: ");
int quantity = input.nextInt();
if (cost > 0 && quantity > 0){


if(quantity >= 10 && quantity <=19){
     discount1 = (double)20/100;
}
else if(quantity >= 20 && quantity <=49){
    discount1 = (double)30.0/100;
}   
else if(quantity >= 50 && quantity <=99){
     discount1 = (double)40.0/100;
}
else if(quantity >=100){
    discount1 = (double)50.0/100;

}

}
 else {

    System.out.println( " please enter valid input ");
}
double total1 = cost * quantity;
dicount_amount = total1 * discount1; 
total=  total1 - dicount_amount;

System.out.println("Total Cost: " + total);

输出:

Enter the cost of the software:15 
Enter the quantity sold:16 
Total Cost: 192.0
相关问题