Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to print my polynomial exponents in superscript with C++? [duplicate]

Tags:

c++

I am just wondering if there is any way to print a polynomial in a way like you write it on paper.

On computers, we usually write: 2x^2

But I want it to look like: 2x2

like image 747
Khalid Badawi Avatar asked Dec 19 '25 13:12

Khalid Badawi


2 Answers

For consoles with fixed pitch fonts, try the old fashioned method:

std::cout << "  2\n";
std::cout << "2x\n";

The superscript is printed on the first line, then the terms on the second line.

like image 102
Thomas Matthews Avatar answered Dec 21 '25 04:12

Thomas Matthews


It is possible to do this, but how you'll do it might depend on which system you're on.

I recently worked on a C++ project where I wanted to display subscripts and superscripts for readability's sake, along the lines of what you're proposing here. The challenge is that, on most systems, the char type does not let you store values corresponding to those superscripts. There are Unicode characters for those superscripts, and many C++ compilers will let you compile code containing those characters as long as you store them as strings. For example, I made this std::unordered_map to map from digits to superscripts:

    /* Map from numerals to their superscript equivalents. */
    const std::unordered_map<char, std::string> kSuperscripts = {
        { '0', "⁰" },
        { '1', "¹" },
        { '2', "²" },
        { '3', "³" },
        { '4', "⁴" },
        { '5', "⁵" },
        { '6', "⁶" },
        { '7', "⁷" },
        { '8', "⁸" },
        { '9', "⁹" },
    };

My compiler interprets these in UTF-8 format, so when I want to display them I can write things like

std::cout << kSuperscripts.at('0') << std::endl;

and it'll print to the console.

Some systems use other encodings besides UTF-8 or some similar Unicode encoding. Not all C++ compilers can accept these characters in their source code, and some compilers might compile using a code page other than the one that the native system uses. But it might be worth trying out something like this to see whether it works on your machine.

like image 44
templatetypedef Avatar answered Dec 21 '25 06:12

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!