# floating point exercise for beginners

Page 1 of 1

## 13 Replies - 2040 Views - Last Post: 01 February 2012 - 05:35 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=265052&amp;s=f1e3b1126f42261d9ecaf811f1d90b0f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Bryston

Reputation: 15
• Posts: 125
• Joined: 24-January 12

# floating point exercise for beginners

Posted 01 February 2012 - 11:59 AM

I just happened to notice in another post...

Jim Blumberg posted

Quote

I would suggest that you look at the documentation for printf(), pay particular attention to the width and precision modifiers.

This link may explain the width and precision modifiers a little better.
Jim

regarding formatting numbers.

I have a similar question re: floating point numbers, the questions are in the comments of the code. I would be interested in how other beginners would attack the problem as well, sharing ideas and all that stuff.

Bear with my programming style, I am trying something newsince I started reading Practical C++ Programming from O'Reilly, awesome book with many insights into programming in general.

On with the code.

```/*************************************************************************/
/*  sphere.cpp: -- program to calculate the volume of a sphere           */
/*                                                                       */
/*  Author: -- Bryston                                                   */
/*                                                                       */
/*  PURPOSE: -- Practical C++ exercise 5-2                               */
/*                                                                       */
/*  USAGE: -- user enters a number                                       */
/*                                                                       */
/*************************************************************************/

#include<iostream>// for all the i/o goodness
#include<iomanip>
using namespace std;// so we don't have to use verbose std::cin etc...

// Global Variables
const long double PI=3.1415926; // declare PI as a constant
long double sphere_volume=0.0; //volume of the sphere
long double r_cubed=0.0; //the value of the radius cubed

/**************************************************************************
******************************** WARNING **********************************
******************* IF YOU STEAL THIS CODE AND SUBMIT IT ******************
*********** AND END UP FLIPPING BURGERS FOR THE REST OF YOUR LIFE**********
***************************************************************************
**************************************************************************/

int main(){

//>>>>>>>>>>>>>>>>>>>>> Initial Display Section <<<<<<<<<<<<<<<<<<<<<<<<<<<
while (1){
cout << endl << "Calculate the volume of a sphere!";
cout << endl << "The user supplies the radius of the sphere.";
cout << endl << "Will display the results of ((4/3)*PI)*r^3";
cout << endl << endl << "Please enter the value for r (0 to exit):> ";

//>>>>>>>>>>>>>>>>>>>>> Get User Input Section <<<<<<<<<<<<<<<<<<<<<<<<<<<<

cin >> sphere_radius;// user supplied floating point value

if (sphere_radius == 0)// give the user a way to exit the program
break;// exit the while loop

//>>>>>>>>>>>>>>>>>>>>> Process Data Section <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

/* Calculate volume of a sphere from known radius supplied by the user.
Using the variable r_cubed to make the actual formula flow a little
better. Could have done it by including the cmath header file
and using pow(r,3) */
// remember to use the decimal point for type float or double!!!
sphere_volume = ((4.0 / 3.0) * (PI * r_cubed));

//>>>>>>>>>>>>>>>>>>>>> Display Results Section <<<<<<<<<<<<<<<<<<<<<<<<<<<

/************************ UNEXPECTED RESULTS *****************************/

// any input that yields a result higher than 99999.9 (approx 28.75)
// will cause the decimal point to go POOFng
// compiled it in DevC++ and Visual C++2010 with equal results
// using setprecision(n) from <iomanip> gives a better result
// but doesn't scale well to a wide range of inputs
// too precise for small inputs && not precise enough for large inputs
// input of 2880 once again strips the decimal if setprecision(12)
// is there a way to use setprecision or something else to force
// a result that is always exactly (n) digits after the decimal point?

cout << endl << endl << "A sphere with the radius : " << sphere_radius;
cout << " units" << endl << "has a volume of ";
// setprecision(n) inline helps preserve the decimal up to a point
cout << setprecision(12) << sphere_volume << " cubic units.";
cout << endl << endl;

}// end while loop
return (0);
}// end function main

```

Is This A Good Question/Topic? 0

## Replies To: floating point exercise for beginners

### #2 jimblumberg

Reputation: 5487
• Posts: 17,062
• Joined: 25-December 09

## Re: floating point exercise for beginners

Posted 01 February 2012 - 12:34 PM

Since you are using C++ you should investigate the ios::fixed, setprecision() and possibly setw() manipulators.

Also in future ask your questions in the body of the post, not in the title or code.

Jim

### #3 CTphpnwb

• D.I.C Lover

Reputation: 3795
• Posts: 13,738
• Joined: 08-August 08

## Re: floating point exercise for beginners

Posted 01 February 2012 - 12:34 PM

printf works for me.
```#include <iostream>

int main(){
double x = 1000.1, y = 0.123456;
printf("%1.5f \t%1.5f\n\n", x, y);
return 0;
}

```

### #4 jimblumberg

Reputation: 5487
• Posts: 17,062
• Joined: 25-December 09

## Re: floating point exercise for beginners

Posted 01 February 2012 - 12:38 PM

Quote

printf works for me.

That should work if you include the cstdio header. But I don't recommend mixing C-stdio functions with C++ streams. If you want printf() type functionality in C++ I suggest you use the boost::format class.

Jim

This post has been edited by jimblumberg: 01 February 2012 - 12:38 PM

### #5 Bryston

Reputation: 15
• Posts: 125
• Joined: 24-January 12

## Re: floating point exercise for beginners

Posted 01 February 2012 - 12:55 PM

Quote

Since you are using C++ you should investigate the ios::fixed, setprecision() and possibly setw() manipulators.

Also in future ask your questions in the body of the post, not in the title or code.

Jim

```    cout << endl << endl << "A sphere with the radius : " << sphere_radius;
cout << " units" << endl << "has a volume of ";
cout << fixed;
cout << setprecision(4) << sphere_volume << " cubic units.";
cout << endl << endl;

```

That solves that problem. Took a few minutes to figure out that 'fixed' was required.
Thanks Jim

### #6 CTphpnwb

• D.I.C Lover

Reputation: 3795
• Posts: 13,738
• Joined: 08-August 08

## Re: floating point exercise for beginners

Posted 01 February 2012 - 01:53 PM

I'm confused. Isn't the code C++? It looks like it to me: .cpp, iostream, Practical C++ exercise 5-2, etc.

### #7 vividexstance

• Tiocfaidh ár lá

Reputation: 792
• Posts: 2,873
• Joined: 31-December 10

## Re: floating point exercise for beginners

Posted 01 February 2012 - 02:46 PM

printf is a function from the standard C library.

*EDIT*: CTphpnwb what compiler do you use? I tried to compile this:
```#include <iostream>

int main()
{
printf("Hello, World!\n");
}

```

with g++ 4.6.1, compile command:

Quote

g++ iostream_test.cpp -o iostream_test

and this is what I received:

Quote

iostream_test.cpp: In function ‘int main()’:
iostream_test.cpp:6:26: error: ‘printf’ was not declared in this scope

This post has been edited by vividexstance: 01 February 2012 - 02:54 PM

### #8 Bryston

Reputation: 15
• Posts: 125
• Joined: 24-January 12

## Re: floating point exercise for beginners

Posted 01 February 2012 - 02:53 PM

Quote

printf is a function from the standard C library.

Why do so many people still use it (other than the fact that they may end up working on legacy code)?
Same with other C stuff that has been improved on with C++?

### #9 vividexstance

• Tiocfaidh ár lá

Reputation: 792
• Posts: 2,873
• Joined: 31-December 10

## Re: floating point exercise for beginners

Posted 01 February 2012 - 03:03 PM

Well if you either working on or just writing code in C, you can't use the C++ library so you need to make use of the standard C library. Even though one of C++ principles is that "you don't pay for what you don't use", some people still think that C++ is bloated and therefore that C is faster. So they just stick with C and use the standard C library.

### #10 CTphpnwb

• D.I.C Lover

Reputation: 3795
• Posts: 13,738
• Joined: 08-August 08

## Re: floating point exercise for beginners

Posted 01 February 2012 - 03:08 PM

```[Session started at 2012-02-01 16:58:36 -0500.]
GNU gdb 6.3.50-20050815 (Apple version gdb-1461.2) (Fri Mar  5 04:43:10 UTC 2010)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys006
run
[Switching to process 3660]
1000.10000 	0.12346

Running…

```

Defaults to GCC 4.2

Found it. XCode defaults to "Link with Standard Libraries" so that if you use C code it will be available and if you don't it won't use the libraries.

### #11 vividexstance

• Tiocfaidh ár lá

Reputation: 792
• Posts: 2,873
• Joined: 31-December 10

## Re: floating point exercise for beginners

Posted 01 February 2012 - 03:11 PM

That output is from gdb, just run gcc with the -v option and it will give you a lot of information about your compiler. Just so you know, gcc 4.2 came out on May 13, 2007!

This post has been edited by vividexstance: 01 February 2012 - 03:12 PM

### #12 Karel-Lodewijk

Reputation: 454
• Posts: 864
• Joined: 17-March 11

## Re: floating point exercise for beginners

Posted 01 February 2012 - 03:32 PM

CTphpnwb said:

```#include <iostream>

int main()
{
printf("Hello, World!\n");
}

```

This will not compile because you forgot to include a necessary header, add #include <cstdio>

Quote

Why do so many people still use printf (other than the fact that they may end up working on legacy code)?
Same with other C stuff that has been improved on with C++?

C is for almost all practical purposes a subset of C++. As such it is a part of C++. C-style code within C++ is not legacy code. C++ offers streams as an additional way to deal with output, whether it is an improvement is in the eye of the beholder.

I'm very much a C++ programmer and will usually use cout over printf But if I want to print a floating point value with 5 decimals, i will use the printf statement CTphpnwb suggested rather than the 5 quite verbose lines in Bryston's reply.

If you do use C-style code, then do follow the conventions set forth in the C++ standard to deal with C code. Meaning you should include standard C headers with the name cheader instead of header.h. And you should assume things from the C standard library are in the std namespace i.e.: std::printf or a using namespace std; anything else is deprecated and support for it could be dropped by a compiler although I don't see it happening any time soon.

EDIT: Due to misquoting I accidently made it look as if I was trying to correct vividexstance

This post has been edited by Karel-Lodewijk: 01 February 2012 - 03:49 PM

### #13 vividexstance

• Tiocfaidh ár lá

Reputation: 792
• Posts: 2,873
• Joined: 31-December 10

## Re: floating point exercise for beginners

Posted 01 February 2012 - 03:36 PM

Karel-Lodewijk, on 01 February 2012 - 05:32 PM, said:

This is because you forgot to include the necessary headers #include <cstdio>

I wasn't asking for help or for a reason why the program didn't compile, I was showing CTphpnwb that the code he/she posted didn't compile.

### #14 CTphpnwb

• D.I.C Lover

Reputation: 3795
• Posts: 13,738
• Joined: 08-August 08

## Re: floating point exercise for beginners

Posted 01 February 2012 - 05:35 PM

It does compile and run in both XCode Version 3.2.2 and Version 4.0.2, probably because XCode defaults to "Link with Standard Libraries" as I mentioned above.