gpt4 book ai didi

java - 使用 for 循环将十进制转换为八进制

转载 作者:行者123 更新时间:2023-11-30 03:04:39 25 4
gpt4 key购买 nike

我的 for 循环遇到问题。 for 循环应该将十进制转换为八进制。有人可以指出我做错了什么吗?

import java.util.Scanner;

public class Dboh {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int decimal = input.nextInt();
int single;
int val;

//Binary
String binaryString = "";
int value = decimal;
while (value != 0) {
binaryString = value % 2 + binaryString;
value = value / 2;
}

//Octal
String octalString = "";
for (decimal = val, single = val % 8, octalString = single + octalString, val = val / 8) {


//Hexadecimal


System.out.println("Decimal" + "\t" + "Binary" + "\t" + "Octal" + "\t" + "Hexadecimal");
System.out.println(decimal + "\t" + binaryString + "\t" + octalString);

最佳答案

像这样改变你的for循环

val = decimal

而不是

decimal = val



for(val = decimal; val > 0; val = val / 8){
octalString = val % 8 + octalString;
}

关于java - 使用 for 循环将十进制转换为八进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35098570/

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