converting to float

Hi all...

I need someone expertise here. Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main (int argc, char* argv[])
{
	int x = atoi (argv[1]);
	int y = atoi (argv[2]);
	int z = atoi (argv[3]);
	if (strcmp(argv[4], "Simple") == 0){ 
		cout<< "Principal = $" << x <<endl;
		cout << "Rate = " <<y <<"% p.a"<<endl;
		cout <<"Time = " << z <<" years"<<endl;
		cout <<"Simple Interest = $" << (x*y/100*z) <<endl;
	}

	cin.ignore (2);
}


I need to convert the output of simple interest to float which is $5184.90 instead of $5180. Any idea how to go about it?
Hi there,

Try this:

cout <<"Simple Interest = $" << (static_cast<float>(x)*y/100*z) <<endl;

What happens is the following: You declare x, y and z as integers, which as you know, have no floating points. When you do a calculation with these integers, the result will always be cast into another integer, unless you are making a calculation between an integer and a floating point type. In that case, the compiler chooses to cast the result to the most exact type. So casting one of them to float or double should solve the problem.

Hope that helps.

All the best,
NwN
Oh I see that! Okay, I get it. Thanks for your help! :)
try this:

#include <iostream>
#include <iomanip>
using namespace std;

int main(int argc, char* argv[])
{
// convert string to integer and storing the first three arguments
double principal = atoi(argv[1]);
double rate = atoi(argv[2]);
int time = atoi(argv[3]);

// declare and initialise variable
double interest = 0.0;
double compoundInterest = 0.0;

// print out arguments
cout << "Principal = $" << principal << endl;
cout << "Rate = " << rate << "% p.a." << endl;
cout << "Time = " << time << " years" << endl;

// compare fourth argument
if (strcmp(argv[4], "Simple") == 0)
{
// output for simple interest found
interest = principal * rate/100 * time;
cout << argv[4] << " interest = $" << fixed << setprecision(2) << interest << endl;
}


added the #include <iomanip> and the "fixed << setprecision(2)" for the output string.
Topic archived. No new replies allowed.