gpt4 book ai didi

java - if 语句中的变量递增

转载 作者:行者123 更新时间:2023-12-01 10:17:11 28 4
gpt4 key购买 nike

这是一段代码(else 子句):

else { // for operators
int count = 1;
if (sub.compareTo("+") == 0){ //if + operator
double d1=stack.pop();
double d2=stack.pop();
answer=d1+d2;
//first two items on stack added
stack.put(answer); // put ans on stack
System.out.println(count+ ") "+d1+ " + " +d2 + " = " +answer); // display ans
count++;
}
if (sub.compareTo("-") == 0){ //if - operator
double d1=stack.pop(); //pop first two items on stack
double d2=stack.pop();
answer =d2-d1; //subtract the items
stack.put(answer);//put ans on stack
System.out.println(count+ ") "+d2+ " - " +d1 + " = " +answer);///display answer
count++;
}
}

此代码尝试使用 stack 来评估基本数学运算。例子有:

  1. 2 + 2 = 4
  2. 4 + 4 = 8

我想使用count变量来显示数字,但它保持为 1。你知道为什么吗?

最佳答案

创建您的 count 全局变量并在函数外部声明它以正确存储值,您所做的是限制 count 的范围,这就是为什么他每次都给您相同的答案

int count=1;  // make sure you count is outside your function 
else{ // for operators

if(sub.compareTo("+")==0){ //if + operator
double d1=stack.pop();
double d2=stack.pop();
answer=d1+d2;
//first two items on stack added
stack.put(answer); // put ans on stack
System.out.println(count+ ") "+d1+ " + " +d2 + " = " +answer); // display ans
count++;
}
if(sub.compareTo("-")==0){ //if - operator
double d1=stack.pop(); //pop first two items on stack
double d2=stack.pop();
answer =d2-d1; //subtract the items
stack.put(answer);//put ans on stack
System.out.println(count+ ") "+d2+ " - " +d1 + " = " +answer);///display answer
count++;
}

关于java - if 语句中的变量递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826108/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com