/ *下面是我的Cookie Clicker解决方案的代码。 我浏览了谷歌提供的4个案例。其中三个案例运行良好,但是,当输入为小数时,输出错误。任何人都可以帮我这个吗? (起初,我认为这只是一个精确的问题,我试图使用大十进制,但它不起作用) 示例(由Google提供)
案例1输入30.0 1.0 2.0 / 案例2输入30.0 2.0 100.0 案例3输入30.50000 3.14159 1999.19990 案例4输入500.0 4.0 2000.0
案例#1:1.0000000 案例#2:39.1666667 案例#3:63.9680013 案例#4:526.1904762 * /
我对案例#3的解决方案 (只有这个案子出了问题,其他人都不错) 请输入C F和X的值 输入:30.5000 3.14159 1999.19990 输出:64.868952130833207547766505740582942962646484375 * /
import java.util.Scanner;
import java.math.BigDecimal;
public class CookieClicker {
public static void main(String[] args) {
double cookie=0; // number of cookies
double current_growth_rate=2.0;
double new_growth_rate=0;
double total_time=0;
double time1=0;
double time2=0;
Scanner input = new Scanner(System.in);
//System.out.println("Please enter the number of cases");
//int numCase = input.nextInt();
//for(int i = 1;i <= numCase;i++ ){
System.out.println("Please enter the value for C F and X");
double C= input.nextDouble();
double F= input.nextDouble();
double X= input.nextDouble(); // total required cookies
while(cookie<X){
time1 = X/current_growth_rate;
//System.out.println("This is time 1 "+time1);
time2 = ((C/current_growth_rate)+(X/(F+current_growth_rate)));
//System.out.println("This is time 2 "+time2);
if(time1>time2){
// deduct C amount of cookies from the total amount of cookies(buy farm)
cookie=cookie-C;
// capture the time that spend on making money to buy a farm
total_time = total_time +(C/current_growth_rate);
//System.out.println(total_time);
current_growth_rate=current_growth_rate+F;
new_growth_rate= current_growth_rate+F;
}
cookie= cookie+current_growth_rate;
}
total_time=total_time+time1;
System.out.println(new BigDecimal(total_time));
//}
}
}
答案 0 :(得分:0)
我使用的是double而不是BidDecimal,我的代码与您的代码非常相似,我可能会帮助您理解代码中的问题。
Scanner scanner = new Scanner(new File(inputFile));
int numberOfTest = scanner.nextInt();
for(int t = 1 ; t <= numberOfTest ; t++) {
double cokkiesRate = 2.0;
double C_FARMCOST = scanner.nextDouble();
double F_COKKIES_PER_SEC = scanner.nextDouble();
double X_TARGET = scanner.nextDouble();
double consumedTime = 0.0;
boolean keeprun = true;
while(keeprun) {
if((X_TARGET - C_FARMCOST)/(cokkiesRate)
< X_TARGET / (cokkiesRate + F_COKKIES_PER_SEC)){
consumedTime = consumedTime + (X_TARGET/cokkiesRate);
cokkiesRate+=F_COKKIES_PER_SEC;
keeprun = false;
}else {
consumedTime = consumedTime + (C_FARMCOST/cokkiesRate);
cokkiesRate+=F_COKKIES_PER_SEC;
}
}
System.out.println("Case #"+t+": "+String.format("%.7f", consumedTime));