Why does this program not accept 'double'?

This program runs fine if I use long and %ld. Why won't it work using double and %f?? HELP!!

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*  This works fine... */

#include <stdio.h>

long cube(long x);

long input, answer;

int again;

main()
{
	printf("Enter an integer value:  ");
	scanf("%ld", &input);

	printf("\n\n\n%ld", input); /* TRACE */

	answer = cube(input);
	printf("\nThe cube of %ld is %ld.", input, answer);

	printf("\nAnother? <hit 1 for yes>...\n");
	scanf("%d", &again);
	
	if(again==1)
	main();

	else	
	return 0;
}

long cube(long x)
{
	long x_cubed;
	x_cubed = x*x*x;

	printf("\n\n\n%ld\n\n\n", x_cubed); /* TRACE */

	return x_cubed;
}


/* This doesn't work */

#include <stdio.h>

double cube(double x);

double input, answer;

int again;

main()
{
	printf("Enter an integer value:  ");
	scanf("%f", &input);

	printf("\n\n\n%f", input); /* TRACE */

	answer = cube(input);
	printf("\nThe cube of %f is %f.", input, answer);

	printf("\nAnother? <hit 1 for yes>...\n");
	scanf("%d", &again);
	
	if(again==1)
	main();

	else	
	return 0;
}

double cube(double x)
{
	double x_cubed;
	x_cubed = x*x*x;

	printf("\n\n\n%f\n\n\n", x_cubed); /* TRACE */

	return x_cubed;
}

[code]
[/code]
Last edited on
This looks like C code, not C++. I would consider the following changes:

0.
Replace <stdio.h> with <cstdio>. (You can ignore this if you do 5 instead.)

1.
Put the variable declarations inside the function where they are used. You do not need them to be global. In fact, you should declare them on the first line where you use them, like this:
 
double answer = cube(input);


2.
The return type of main must be int, otherwise it's not valid C++.

3.
Do not use main() as a recursive function. Explicitly calling the main() function is not common practice. If you need to use recursion, make a new function for it.

4.
Get rid of the recursion. The program would be easier to read if you simply used a loop, like this:
1
2
3
4
5
bool again = true;
while (again) {
   ...
   // update again from user input
}


5.
Use IO streams insted of printf/scanf. These functions are typically used in C, but are considered less safe than the newer stream operations. This way you get rid of all your format string confusion (e.g. %ld vs %f). Example:
1
2
3
4
5
#include <iostream>
// ...

    std::cout << "Enter an integer value: ";
    std::cin >> input;

Last edited on
6.
Use proper indenting.

Bad:
1
2
3
4
5
    if(again==1)
    main();

    else	
    return 0;


Good:
1
2
3
4
    if(again==1)
        main();
    else	
        return 0;

ropez,

Thank you so much. I guess you can tell I'm new to this.

tzuch
Topic archived. No new replies allowed.