英文:
Why am I getting a "/ by zero" error in this program?
问题
/**
* 编写一个关于TicTacToe(井字棋)的类描述。
*
* 作者:(你的名字)
* 版本:(版本号或日期)
*/
import java.util.Scanner;
public class TicTacToe
{
public static void main(){
Scanner s = new Scanner(System.in);
int state = 0, turn = 1, choice, drawcheck=0;
for(int end=0; end==0; end=end){
System.out.println("\u000c");
for(int i =1; i<10; i++){
if(state%(3^i)==0){
System.out.print(" ");
}
else if(state%(3^i)==1){
System.out.print("X");
}
else{
System.out.print("O");
}
if(i%(3^i)==0){
System.out.println("");
}
else{
System.out.print("|");
}
}
System.out.println("输入状态(最大59048)");
state=s.nextInt();
}
}
}
注意:这段代码存在一些问题,其中计算部分的逻辑可能有误,导致了除以零错误。如果你需要修复这段代码,请提供更多上下文,我可以帮助你更正错误。
英文:
/**
* Write a description of class TicTacToe here.
*
* @author (your name)
* @version (a version number or a date)
*/
import java.util.Scanner;
public class TicTacToe
{
public static void main(){
Scanner s = new Scanner(System.in);
int state = 0, turn = 1, choice, drawcheck=0;
for(int end=0; end==0; end=end){
System.out.println("\u000c");
for(int i =1; i<10; i++){
if(state%(3^i)==0){
System.out.print(" ");
}
else if(state%(3^i)==1){
System.out.print("X");
}
else{
System.out.print("O");
}
if(i%(3^i)==0){
System.out.println("");
}
else{
System.out.print("|");
}
}
System.out.println("Enter State (max 59048)");
state=s.nextInt();
}
}
}
I was trying to make a Tic Tac Toe game, but for some reason this gets a Divide by Zero error? I am an absolute coding noob, can someone help? (I know this isn't the game, I was trying to isolate the parts, this one gets the error)
答案1
得分: 9
我有一种感觉,你正在尝试使用模3的i次方。
然而,^
符号表示异或,而不是乘方,所以发生的情况是,你得到了3 % 0,这基本上是零除法。
如果你想要3的i次方,你需要使用Math.pow(3, i)
。
英文:
I have a feeling you are trying to use modulo 3 to the power of i.
However ^
sign means XOR, not power, so it happens, that you get 3 % 0 - which is basically zero division.
If you want to the power i th power of 3 you need Math.pow(3, i)
答案2
得分: 0
你好,似乎你误解了^运算符,它是异或运算符。
因此,当i = 3,用二进制表示为11时,
3^i = 11异或11 => 0
异或是二进制运算符,它比较第i位上的位并在只有一位为1时返回1。这意味着当你对相同的数字进行异或运算时,结果为0。
[更新] 已修正数字3的十进制表示 :p
英文:
Hi seems you have mistaken the ^ operator it is XOR
so when i = 3 in binary 11
> 3^i = 11 XOR 11 => 0
XOR is binary operator and compares bits at i-th index and returns 1 if only one bit at i-th index is 1. This means when you xor same numbers you get 0
[Update] Fixed decimal representation of 3 :p
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论