user1705380
user1705380

Reputation: 79

Type casting int into double C++

I am new to programming and this might be an obvious question, though i cannot for life of me figure out why my program is not returning as a double.

I am suppose to write a stocks program that takes in shares of stock, whole dollar portion of price and the fraction portion. And the fraction portion is to be inputted as two int values, and include a function definition with 3 int values.The function returns the price as a double.

#include <iostream>
using namespace std;

int price(int, int, int);

int main()
{
    int dollars, numerator, denominator, price1, shares;
    char ans;
    do
    {
        cout<<"Enter the stock price and the number of shares.\n";
        cout<<"Enter the price and integers: Dollars, numerator, denominator\n";
        cin>>dollars>>numerator>>denominator;
        cout<<"Enter the number of shares held\n";
        cin>>shares;
        cout<<shares;
        price1 = price(dollars,numerator,denominator);
        cout<<" shares of stock with market price of ";
        cout<< dollars << " " << numerator<<'/'<<denominator<<endl;
        cout<<"have a value of " << shares * price1<<endl;
        cout<<"Enter either Y/y to continue";
        cin>>ans;
    }while (ans == 'Y' || ans == 'y');
    system("pause");
    return 0;
}

int price(int dollars, int numerator, int denominator)
{
    return dollars + numerator/static_cast<double>(denominator);
}

Upvotes: 1

Views: 4365

Answers (2)

wallyk
wallyk

Reputation: 57774

It is because you are returning an int. This will fix it.

double price (int dollars, int numerator, int denominator)
{ 
    return dollars + (double) numerator / denominator;
}

Upvotes: 2

Lews Therin
Lews Therin

Reputation: 10995

That's because your variables are of type int. Hence you are losing precision.

Change your int return types and variables to doubles.

#include <iostream>
using namespace std;
double price(double, double, double);
int main()
{
  double dollars, numerator, denominator, price1, shares;
char ans;
do
{
cout<<"Enter the stock price and the number of shares.\n";
cout<<"Enter the price and integers: Dollars, numerator, denominator\n";
cin>>dollars>>numerator>>denominator;
cout<<"Enter the number of shares held\n";
cin>>shares;
cout<<shares;
price1 = price(dollars,numerator,denominator);
cout<<" shares of stock with market price of ";
cout<< dollars << " " << numerator<<'/'<<denominator<<endl;
cout<<"have a value of " << shares * price1<<endl;
cout<<"Enter either Y/y to continue";
cin>>ans;
}while (ans == 'Y' || ans == 'y');
system("pause");
return 0;
}
double price(double dollars, double numerator, double denominator)
{
  return dollars + numerator/denominator;
}

Upvotes: 3

Related Questions