Search code examples
c++croot-framework

If two digits are the same 0s then make 0 condition in C++ and Root


In my code, legends are running within a loop, and I am trying to show a graph with

0-10%
10-20%

and so on. The problem is when I write this code

legend->AddEntry(gr[i], Form("%d0-%d0 %%",i+0,i+1), "lep");

It shows

00-10%
10-20% etc

So how to not show 00, but 0 in the first line?


Solution

  • A small adaptation of the shown statement should be enough; use:

    legend->AddEntry(gr[i], Form("%d-%d %%", i*10 , (i+1)*10), "lep");
    

    Explanation:

    Form("%d0-%d0 %%",i+0,i+1) seems to be some kind of string formatting, and i your loop variable which runs from 0 to 9, right? The shown Form statement just appends "0" hard-coded to the single digit in i; instead, you can multiply i by 10, resulting in the actual numbers you want printed; and since 10*0 is still 0, this will be a single digit still; so, replace the previous Form(...) call with Form("%d-%d %%", i*10, (i+1)*10) and you should have the result you want!

    In case you're worrying that printing i*10 is "less efficient" than printing i with "0" suffix - don't. The formatting and output of the string is most probably orders of magnitude slower than the multiplication anyway, so any overhead of doing multiple multiplications is negligible.