Posts Tagged ‘Header Files’

How to set precision in C++

June 1, 2009

In C++, you can use the ‘precision’ function to set the precision of the output. The function ‘precision’ is present in the header file ‘iostream.h’. The following,

cout.precision(n);

will have totally print ‘n’ d igits in the output with the decimal point in between(say ‘x’ before the decimal and ‘n-x’ after the decimal. The value of x will depend on the result). For example, if n = 4, the result is

0.2727 for 3/11, and
1.272 for 14/11

The example illustrated below provide a clear guidance on how to use the precision function. The Problem is to find the sum of ‘n’ numbers and then print the output in a single line.

#include<iostream>

using namespace std;

int main()
{
double a,s=0;
while( cin >> a )
{
s += a;
}
cout.precision(15);
cout<<s<<‘\n’;
return 0;
}

Advertisements

How to create header files in C/C++ ?

February 25, 2009

First of all, does creating a header file useful at all ? If yes how ?

It obviously is or else we wouldn’t have had soemthing called a ‘header files’.

Next, can we create our own header files ?

Yes, you can. It is pretty simple and its going to make your program simple and customizable.

Let us start with creating a header file in the traditional TurboC. Define the contents of the header file (meaning the functions you would like to include in the file) and then save it as a ‘.h’ file in the ‘include’ directory.

The path could be C:/TC/INCLUDE if you have installed Turbo C directly in ‘drive C’.

Your are done !! 🙂 Include the header file in the program by just including the file like any other file.

#include “headerfilename.h” or #include<headerfilename.h>

Creating one in GCC is a bit more difficult. Define the file in the same way as stated above and save it in a ‘directory where you are going to save the program’ (NOTE: This is important. Both the header file and the program must be in the same directory, if not the program will not be able to detect your header file ). Header File successfully created ! 🙂 But, unlike Turbo C the header file cannot be included by

#include<headerfilename.h>

The only way to include the header file is to treat the filename in the same way u treat a string.

#include “headerfilename.h”

Now that you have created your header files, you can create the function like sort, factorial etc. and store them in the header file. When you intend to use them, include the header file in the program and just call the function you stored in the header file.

Hasn’t it made life simple ? 😀

%d bloggers like this: