-5

why is that when I print a result from my function, it prints out 0? I tried using a prototype, and followed an example from my teacher, but no dice. Pretty lost here.

#define _CRT_SECURE_NO_WARNINGS #include <stdlib.h> #include <stdio.h> #include <math.h> double energie_cinetique(double m, double v) { double resultat; resultat = 1 / 2 * m * (v * v); return resultat; } int main(void) { double reponse; reponse = energie_cinetique(10, 5); printf("Energie pour m=10 kg et v=5 m/s: %d", reponse); system("pause"); return EXIT_SUCCESS; } 
2
  • 4
    Integer arithmetic. Commented Nov 16, 2017 at 2:58
  • Maybe use %lf instead of %d in your printf() statement. Also it maybe a good idea to use 1.0/2.0 * m * (v * v) to ensure floating point arithmetic. Or else 1/2 integer division is 0 and 1.0/2=0.5 or 1/2.0=0.5 or 1.0/2.0=0.5 Commented Nov 16, 2017 at 3:00

2 Answers 2

6

Integer division with 1/2 = 0 so your result will be zero.

Change the half to 0.5 and you should be golden for the math part (also, multiplication is faster so use it instead of division when possible).

%d in the printf is for int types, use %f instead for a double.

After that it should work.

Sign up to request clarification or add additional context in comments.

Comments

2

There are two errors here:

First, 1 / 2 == 0, obviously because they are integers. Change to

1.0 / 2.0 * m *(v * v); // OR 0.5 * m * (v * v); 

Second, %d is a format specifier for signed integers. Using it to print double precision FP is UB. Your compiler should have already warned about this. You should write

printf("... %lf ...", ...); ^~~ 

Then the output should be correct.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.