2012-10-04 107 views
1

我是編程新手,這可能是一個明顯的問題,但我不能爲我的生活弄清楚爲什麼我的程序沒有返回作爲一個雙。類型鑄造int到雙C++

我想寫一個股票計劃,需要股票的股票,價格的整個美元部分和分數部分。小數部分將作爲兩個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); 
} 
+1

「該函數返回雙倍價格。」嗯,不,畢竟,你有'int'作爲返回類型。 – GManNickG

+0

Gack。沒有人再用股票來做股票價格。這都是小數。 –

回答

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

我可以將它們全部設置爲雙打,但我的任務指出用戶應該輸入3個int值,並在函數定義中包含3個int參數。讀這個我假設我將不得不stac_cast和int到一個雙,但它似乎並沒有工作。我已經嘗試過Wallyk在Num/Denom中放置(Double)的建議,儘管它沒有將我的答案變成雙重 – user1705380

+0

你可以做的是返回一個double。然後,函數定義似乎沒有指定返回類型是。所以使用double而不是int。 嘗試static_cast或強制轉換爲double,但該函數返回的結果*必須是double。你的任務有一些奇怪的要求:( –

+0

Thx。反饋幫助了一大堆!現在得到它! – user1705380

2

這是因爲你正在返回一個int。這將解決它。

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