0

Questions

Some calculations are giving me the wrong answers. Can someone tell me the proper way to carry out math operations? (as in what data types to use for the numbers and so on)

// setup code
#include <stdio.h>

int num1 = 24;
int num2 = 7;
float result;


// main code
int main() {
    printf("this is x:%d\n", num1);
    printf("this is y:%d\n", num2);

    result = num1 / num2; // this outputs 0 
    printf("this is int of x/y: %d\n", result);
    
    result = (float) num1 / num2; // this outputs -536870912
    printf("this is float of x/y: %d", result);

    return 0;
}
// end

the first output is 0. I thought it would be 3

the second output is -536870912. I thought it would be 3.42


I've tried using other datatypes and typecasting which worked but I can't remember what they were and this is the code that I would like to use anyways.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
X2Zii
  • 11
  • 4

1 Answers1

1

There are several different issues with your code. These issues interfere with eachother and produce the surprising results you've seen.

Issues directly causing the weird behaviour you've seen:

  • result is declared as float, so in both cases, result = num1 / num2 will be calculated as a float, not as an int.
  • When printing a float with printf, you must use "%f", not "%d". "%d" is for int.

Int and float are stored internally using a different encoding, so if a variable is float and you tell printf it's an int, or vice-versa, printf is inevitable going to display a bunch of garbage.

Other issues:

  • Your variables should be declared inside main, not outside main.
  • Your second printf is missing a \n, which means it might not be printed at all, and if it's printed in a console, it will mess up the display a bit.

Finally, a piece of warning about casting and order of operations:

  • In order to perform floating-point division, the correct operation is ((float) num1) / num2, not (float) (num1 / num2). This is because (num1 / num2) is integer division and results in 3; once you have 3, it's too late, if you cast to (float) you'll get 3.0, not 3.42.
  • When you write (float) num1 / num2, do you know whether this is interpreted as ((float) num1) / num2 or as (float) (num1 / num2)? If you do, good, but if you don't, then don't write that.

Correct code:

#include <stdio.h>

int main() {
    int num1 = 24;
    int num2 = 7;
    int integer_quotient;
    float float_quotient;

    printf("this is x:%d\n", num1);
    printf("this is y:%d\n", num2);

    integer_quotient = num1 / num2;
    printf("this is int of x/y: %d\n", integer_quotient);
    
    float_quotient = ((float) num1) / num2;
    printf("this is float of x/y: %f\n", float_quotient);

    return 0;
}
Stef
  • 13,242
  • 2
  • 17
  • 28
  • 1
    Thanks this answers all the questions I needed answers to. The code was a testing environment to learn those functions as I'm learning c. – X2Zii Mar 01 '23 at 08:01