Returning incorret Answer

Please see below my code. I cant work out why I do not get the correct answer the answer should be 62.8

My code returns a result of 62

I am stumped!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <stdio.h>

int main()
{
   printf("\n");
       	printf("QUESTION\n");
	printf("\n");
	printf("Calculate the circumfrence of a circle knowing the diameter?\n");
	printf("\n");
	printf("Formula Pid\n");
	printf("\n");
	printf("Declerations\n");
	printf("\n");
	printf("Pi = 3.14\n");
	printf("\n");
	printf("d = 20\n");
	printf("\n");
int pi=3.14;
int d=20;
int answer=pi*d;
printf("the answer is  %i\n",answer);
printf("\n");
    	// make the program wait for a new line to be entered
    puts( "press ENTER to quit" ) ;
    int c = 0 ;
    while( c != '\n'  && c != EOF ) c = getchar() ;

    return(0);
}
All your variables are of type int. An integer is always a whole number, it cannot have any decimal places.

Use type double or float instead.
Everyone knows The Answer to the Ultimate Question of Life, the Universe, and Everything is 42. http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker's_Guide_to_the_Galaxy

You're trying to do floating point calculation using integers.
pi, d and answer are all ints. You're also trying to print the answer as an int.
pi and d are type of int. Use double
Thank you, I changed it to double and got a returned answer of

1717986919
However float returned the correct answer. I don't understand why
You need to use the correct printf format specifier. %f rather than %i

http://www.cplusplus.com/reference/cstdio/printf/

This code is actually C, rather than C++.
printf("the answer is %f\n\n",answer);

The C++ version would be:
std::cout << "the answer is " << answer << '\n' << std::endl;


Last edited on
Thanks very much for all the help working fine now. Can someone point me in the direction as to how the code asks questions you input the information and then it does the calculation.
Topic archived. No new replies allowed.