2010-01-24 195 views
1
#include <iostream> 
using namespace std; 
/*Use void functions, they perform some action but do not return a value*/ 

//Function Protoype, input,read in feet and inches: 
void input (double& feet, double& inches); 
//Function Prototype, calculate, calculate with given formulae. 
void calculate(double& feet, double& inches); 
//Function Prototype, output, outputs calculations to screen. 
void output (double meters, double centimeters); 

int main() 
{ 
    double feet; 
    double inches; 
    char repeat; 

    do 
    { 
     //Call input: 
     input(feet, inches); 
     //Call calculate: 
     calculate(feet, inches); 
     //Call output: 
     output (feet, inches); 
     cout << "\n"; 
     cout << "Repeat? (Y/N): "; 
     cin >> repeat; 
     cout << "\n"; 
    } 
    while (repeat == 'Y' || repeat == 'y'); 
} 

//Input function definition: 
void input (double& feet, double& inches) 
{ 
    cout << "Please enter the length in feet" << endl; 
    cin >> feet; 

    cout << "Please enter the length in inches" << endl; 
    cin >> inches; 
} 

//Calculate function definition, insert formulae here: 
void calculate (double& feet, double& inches) 
{ 

    feet = (feet * 0.3048); 
    inches = (inches * 2.54); 
} 

//Output function definition: 
void output (double meters, double centimeters) 
{ 
    cout << meters << " meters & " << centimeters << " cm's. " << endl; 
} 

爲什麼我的轉換不起作用? 或我在做什麼錯?C++轉換不起作用

目標:給定長度以英尺和英寸爲單位,我假設輸出相當於米和釐米的長度。

//Calculate function definition, insert formula here: 
void calculate (double& feet, double& inches) 
{ 
    feet = (feet * 0.3048); 
    inches = (inches * 2.54); 
} 
+3

在SO上發佈問題時,您需要提供儘可能多的相關信息。在這種情況下 - 你如何調用函數? 「不工作」是什麼意思?你得到什麼錯誤信息? – 2010-01-24 12:33:44

回答

7

這似乎是一個奇怪的做法,改變實際的輸入變量。我反而選擇:

void calculate (double feet, double inches, double& meters, double& centimeters) { 
    double all_inches = feet * 12.0 + inches; 
    centimeters = all_inches * 2.54; 
    meters = int (centimeters/100.0); 
    centimeters -= (meters * 100.0); 
} 

在任何情況下,即使你使用相同的變量輸入和輸出(然後他們應該被重新命名爲更合適的東西),它仍然是最容易轉化爲一個單一的形式(英寸),然後轉換爲釐米,然後回到米/釐米。

在你當前的代碼中,如果你傳遞1ft,0in,你會得到0.3048m,0cm而不是更正確的30.48cm。通過使用此答案中的代碼,它將首先轉換爲12.0英寸,然後從那裏轉換爲30.48釐米,然後轉換爲0米,30.48釐米。同樣,四英尺半英寸(4英尺,6英寸)將首先轉換爲54英寸,然後轉換爲137.16釐米,然後轉換爲1米,37.16釐米。

+0

謝謝Paxdiablo的解釋。 – user242229 2010-01-24 12:47:37

+0

沒有probs,樂意幫忙。 – paxdiablo 2010-01-24 13:10:07

4

你沒有把英寸加到腳上的結果。