输入int into double C ++

时间:2012-10-04 21:23:24

标签: c++ windows casting

我是编程新手,这可能是一个显而易见的问题,虽然我不能终身解决为什么我的程序没有作为双重返回。

我想写一个股票计划,它接受股票,全部美元价格部分和分数部分。并且小数部分将作为两个int值输入,并包括具有3个int值的函数定义。该函数将价格返回为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);
}

2 个答案:

答案 0 :(得分:3)

那是因为你的变量属于int类型。因此你正在失去精确度。

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

答案 1 :(得分:2)

这是因为你要归还int。这将解决它。

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