gpt4 book ai didi

C - 模 (%),如何计算 IntToString 转换的值,其中 num/= 10

转载 作者:行者123 更新时间:2023-11-30 17:38:45 25 4
gpt4 key购买 nike

public static final int MAX_DIGITS = 10;

String intToStr( int num ){
int i = 0;
boolean isNeg = false;
char[] temp = new char[ MAX_DIGITS + 1 ];

if( num < 0 ){
num *= -1;
isNeg = true;
}

// Fill buffer with digit characters in reverse order
while(num != 0){
temp[i++] = (char)((num % 10) + ‘0’);
num /= 10;
}

StringBuffer b = new StringBuffer();
if( isNeg )
b.append( ‘-’ );

while( i > 0 ){
b.append( temp[--i] );
}

return b.toString();
}

我能否获得一些帮助来理解以下代码行:

    // Fill buffer with digit characters in reverse order 
while(num != 0){
temp[i++] = (char)((num % 10) + ‘0’);
num /= 10;
}

据我了解,如果 num = 732,且 i = 0:

temp [0] = "2"; //732 % 10 = 73.2 so 2 is the remainder?
num = 73.2; //732 divided by 10
temp [1] = "32"; //73.2 % 10 = 7.32 so 32 is the remainder?
num = 7.32; //73.2 divided by 10
temp [2] = "732"; //7.32 % 10 = 0.732 so 732 is the remainder?
num = 0.732; //7.32 divided by 10

num 现在小于零,所以继续。

然而,现在我们正在倒退:

    while( i > 0 ){
b.append( temp[--i] );
}

但是我从物理计算中看到的是:

String str = temp[2] + temp[1] + temp[0]; 
str = "732" + "32" + "2";

实际发生的是 temp 正在存储:

    temp[2] = 7; 
temp[1] = 3;
temp[0] = 2;

获取:

   str = "732";

但我不明白 temp 如何只得到一个数字。

最佳答案

那么让我们运行一下您的程序。

// Fill buffer with digit characters in reverse order 
while(num != 0){
temp[i++] = (char)((num % 10) + ‘0’);
num /= 10;
}

When i is 0 and num is 732
first case
temp[0] = (char)((732%10) +'0');
temp[0] now has the value of 2
next line 732/=10
num = 73
tem[1] = (char)((73%10 +'0');
temp [1] now has the value of 3
next line 73/=10
temp[2] = (char)((7%10 +'0');
temp[2] now has the value of 7

关于C - 模 (%),如何计算 IntToString 转换的值,其中 num/= 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047537/

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