0

我正在尝试制作一种算法来执行以下操作:

64 
797
  7
===
 79

这将需要 7,乘以 7,然后写下答案的最后一位数字,然后将其乘以 7,然后将 7 的第一位数字加上 7,依此类推 - 所以如果你做 3 次(写下它下来),你得到我在那里写的乘法。

我得到了一个不好的代码,而不是以这种形式显示(例如)上面的内容:

7,9,4
9,7,6

等等我得到这样的东西:

7, 9, 52
9, 55, 54

我的代码:

    for(int i = 0; i<3; i++){//Run the code three times
        temp=upper*7%10+tens;//get the temp but keeping the upper because I am going to need it for the tens part
        tens=(upper*7+"").charAt(0);//get the first character of upper*7
        System.out.println(upper+", "+temp+", "+tens);
        upper=temp;
    }

据我所知,问题出在 charAt 中,因为显然 7*7 的第一个字符不是 52。

编辑 现在代码工作正常,我还有另一个问题。我尝试了我的新工作代码(将 tens 作为 char 的字符串值的 int 值,而不仅仅是 char),我还有另一个问题。万岁!

Last tens: 0  Now's plain number:7, New:9, Tens:4
Last tens: 4  Now's plain number:9, New:7, Tens:6
Last tens: 6  Now's plain number:7, New:15, Tens:4
Last tens: 4  Now's plain number:15, New:9, Tens:1
Last tens: 1  Now's plain number:9, New:4, Tens:6

我的代码现在与旧代码相同,只是固定了十位。但是现在,我得到了 15 个数字。那应该是一个数字。怎么了?老实说,我不知道我写的代码是否能实现我的目的。什么代码会?

4

1 回答 1

0

我强烈怀疑问题出在tens. 您尚未在代码中显示此内容,但我怀疑它是int.

所以这一行:

tens = (upper*7+"").charAt(0);

从字符串中取出第一个字符,然后将其存储在int. 例如,字符 '4' 是 Unicode 52 ('0') 是 48。转换为int只是将 UTF-16 代码单元从无符号的 16 位值转换为有符号的 32 位值。

然后您将显示tens- 但如果tens确实是 an int,它将显示为 number

据我所知,问题出在 charAt 中,因为显然 7*7 的第一个字符不是 52。

那么,7*7 的字符串表示的第一个字符将是“4”。当它被转换为 时int,你会看到它是 52。

如果您只想tens作为 a char,则应将其声明为 type char。当然,您不应该使用该值进行算术运算 - 但是当您显示它时,您会看到 4 显示,因为字符串转换仍会将其视为字符而不是数字。

于 2014-05-21T15:08:00.133 回答