-1

The order of magnitude is not correct:

#include <stdio.h>
#include <math.h>
#define M_H 1.007975/(6.02214076*pow(10,23)*1000)
#define k_B 1.380649*pow(10,-23)
int main()
{
    printf("%G\n",M_H);
    printf("%G\n",k_B);
    printf("%G\n",M_H/k_B);
    return 0;
}

Because it gives:

1.67378E-27
1.38065E-23
1.21232E-50

And i need that constants as defined.

I used gcc 12.2.1-1 with the -lm flags. I was expecting:

1.67378E-27
1.38065E-23
1.21232E-4
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • 2
    operator precedence, reminder that macros are just text substitution – pm100 Jan 26 '23 at 18:25
  • 2
    In `M_H/k_B`, do you really want `1.007975 / (6.02214076 * pow(10,23) * 1000) / 1.380649 * pow(10,-23)` or do you want `(1.007975 / (6.02214076 * pow(10,23) * 1000)) / (1.380649 * pow(10,-23))`? – Ted Lyngmo Jan 26 '23 at 18:25
  • 3
    GERMÁN ORLANDO CUEVA ESTRADA, Why code `1.380649*pow(10,-23)` and not `1.380649e-23`? – chux - Reinstate Monica Jan 26 '23 at 18:30
  • You macros shouldn't be calling `pow` at all. It makes no sense. `pow(10, -23)` is just `1e-23`. Have you never seen scientific notation before? – Tom Karzes Jan 26 '23 at 18:33
  • 1
    GERMÁN ORLANDO CUEVA ESTRADA, `f*pow(10, p)` risks loss of precision. Note that `1.380649e-17 != (1.380649*pow(10,-17))`. Best to form your constants directly. – chux - Reinstate Monica Jan 26 '23 at 18:37
  • Unrelated: The Avogadro constant is 6.02214076E+23. Why do you divide the atomic weight of hydrogen by 6.02214076E+26? – Ted Lyngmo Jan 26 '23 at 18:57

2 Answers2

7

M_H/k_B expands to:

1.007975/(6.02214076*pow(10,23)*1000)/1.380649*pow(10,-23)

Note that the 2nd pow is not enclosed in parentheses, and therefore the multiplication is done after the preceding division. You should wrap your defines in parentheses to prevent that:

#define M_H (1.007975/(6.02214076*pow(10,23)*1000))
#define k_B (1.380649*pow(10,-23))

I'd also recommend you to replace the pow function call with the 1e-23 syntax (aka scientific notation); this way the number in k_B will be parsed as a single token, and the parentheses would not be necessary there:

#define M_H (1.007975/6.02214076e26)
#define k_B 1.380649e-23

and i need that constants as defined

If, for some reason, you cannot modify those definitions, you can still add the parentheses at the point of use:

printf("%G\n",(M_H)/(k_B));
Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
1

do

#define M_H (1.007975/(6.02214076*pow(10,23)*1000))
#define k_B (1.380649*pow(10,-23))

to ensure correct order

pm100
  • 48,078
  • 23
  • 82
  • 145