Output a number raised to a power as a string

ぐ巨炮叔叔 提交于 2019-12-02 13:48:11

问题


I am new to Java and I'm not quite sure how to output an integer raised to a power as a string output. I know that

Math.pow(double, double)

will actually compute the value of raising a double to a power. But if I wanted to output "2^6" as an output (except with 6 as a superscript and not with the carat), how do I do that?

EDIT: This is for an Android app. I'm passing in the integer raised to the power as a string and I would like to know how to convert this to superscript in the UI for the phone.


回答1:


If you're outputting the text to the GUI then you can use HTML formatting and the <sup> tag to get a superscript. Otherwise, you'll have to use Unicode characters to get the other superscripts. Wikipedia has a nice article on superscripts and subscripts in Unicode:

http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts




回答2:


Unicode does have superscript versions of the digits 0 to 9: http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

This should print 2⁶:

 System.out.println("2⁶");

 System.out.println("2\u2076");



回答3:


This answer should only be used if using Eclipse (a java editor) what eclipse does is it only supports certain Unicode symbols. 1 2 and 3 can all be done and are supported by eclipse, anything else you have to play with the settings of eclipse which isnt too hard. There's this thing called Windows-1252 which is the default for a lot of stuff it seems, including being the default encoding for files in Eclipse. So, whenever you're printing to the console, that's what it's trying to interpret it as, and it doesn't support the full unicode charset since it's a 1 byte encoding. This isn't actually a problem with the Java, then, it's a problem with Eclipse, which means you need to edit your Eclipse to use UTF-8 instead. You can do this in multiple places; if you just want the unicode characters to be displayed when you're running this one file, you can right click the file, properties -> resource -> text file encoding and change from default to other: utf-8. If you want to do this to your whole workspace, you can go to Window -> Preferences -> General -> Workspace -> Text file encoding. You could also do this project-wide or even just package-wide following pretty similar steps depending what you're going for.



来源:https://stackoverflow.com/questions/12208275/output-a-number-raised-to-a-power-as-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!