1

I declare double variables t and tau, and assign them values 1 and 0.00001 This line of code produces 536870912 in the console. What can be the reason?

printf("%i\n",round(t/(tau*double(2))));

By the way, I write code in a C++ compiler, but practically it's C.

Kalana
  • 5,631
  • 7
  • 30
  • 51
  • 1
    Use `%lf` instead of `%i` – Kalana Apr 12 '20 at 12:44
  • @Kalana this returns me "nan" – Nick The Dick Apr 12 '20 at 12:45
  • 6
    "*but practically it's C*" - No it isn´t. You use `double(2)`, which isn´t possible in C. – RobertS supports Monica Cellio Apr 12 '20 at 12:57
  • Code compiled with a C++ compiler is *by definition* C++ code. You *might* be able to compile it with a C compiler but also might not. Even if it compiles, the behavior might differ. As such, I'll remove the C tag, as you are using C++. – ljrk Apr 12 '20 at 22:01
  • @Kalana This is *is* a C++ queston as the code above is shown to be C++, thus the C tag *is* wrong. Some people watch the C tag and are greatly annoted by C++ questions that are wrongly tagged. My edit was approved by others, please stop reverting these. Additionally, in C++ the header `stdio.h` is not necessarily available or has the intended behavior. One should use the `cstdio` and `cmath` headers instead. There are many minor differences with C and C++, eg. your main function does specify it doesn't take arguments in C++ -- but the same code doesn't do that in C. Stop mingling C and C++. – ljrk Apr 13 '20 at 08:13
  • He trying to run `C` code. There for my answer was based on `C`. If he asked answer for `c++` my answer never be accepted. There for your edit suggestion on my answer was rejected by community not by me. – Kalana Apr 13 '20 at 10:54
  • @Kalana No, `double(2)` is not C code, so he's obviously running C++. I've thus removed the C tag from the question but he's reverted the edit with no reasoning. Also, please tag me when answering, otherwise I won't get notified. – ljrk Apr 18 '20 at 18:24
  • @larkey his first and only tag was `C`. There for my answer was base on `C`. That was actually happened. – Kalana Apr 18 '20 at 18:36
  • @Kalana if you compile code with a C++ compiler, it's C++. And his code was evidently not C, despite his claims. – ljrk Apr 18 '20 at 20:54

2 Answers2

3

round returns a double. Printing it with %i is undefined behaviour.

Use %f for printing double:

printf("%f\n",round(t/(tau*double(2))));
P.P
  • 117,907
  • 20
  • 175
  • 238
2

Use %lf instead of %i and remove double line it is unnecessary because you are already defined variables as double.

#include <stdio.h>
#include <math.h>

int main()
{
    double t = 1, tau = 0.00001;

    printf("%lf\n", round(t/(tau*2)));

    return 0;
}

Output -: 50000.000000


If you want 50000 only you can edit your code into like this

double t = 1, tau = 0.00001;
int answer;

answer = round(t/(tau*2));
printf("%i\n", answer);

Output -: 50000

Kalana
  • 5,631
  • 7
  • 30
  • 51