简体   繁体   中英

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);
}

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM