下面你會發現我創建用戶自定義函數的慘淡嘗試。我正在做一項計算安裝不同形狀地毯的面積和成本的任務。我也想保持它們的總數。此外,該分配要求我使用一個使用過的已定義函數。現在它所做的只是接受1的輸入並詢問「邊的長度是多少:」。然後循環回選擇菜單。它並沒有計算出總計很少的跟蹤總數。我在創建用戶定義的函數時做了什麼錯誤,我如何合併它以保持運行總數直到它們退出?如何在C++中調用用戶定義的函數?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
實際問題是什麼。錯誤消息?意外的行爲? –
現在它所做的只是接受1的輸入並詢問「邊的長度是多少:」。然後循環回選擇菜單。它並沒有計算出總計很少的跟蹤總數。 – BWMustang13
'void square(double)'你甚至不使用輸入參數? 'sqrTot'是'square()'函數的本地代碼,並且將針對每個調用重新計算。 –