简体   繁体   English

将强制类型转换为double C ++

[英]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. 分数部分将作为两个int值输入,并包含具有3个int值的函数定义。该函数将价格返回为两倍。

#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. 那是因为您的变量是int类型的。 Hence you are losing precision. 因此,您将失去精度。

Change your int return types and variables to doubles. 将您的int返回类型和变量更改为双精度。

#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 . 这是因为您要返回一个int This will fix it. 这将解决它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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