我搜索了網際網路的各個角落來尋找這個問題的答案。“做程式設計練習4,但
使用 new 來分配結構體而不是宣告結構體變數。 此外,讓程式在請求披薩公司名稱之前請求披薩直徑。”
我輔修計算機科學,但自從我做任何程式設計以來已經有一段時間了,我想對自己進行測試,加強我所知道的,看看我是否可以自己學習更多。無論如何,我遇到了這個問題,卻找不到一個好的例子來模仿,所以在多次嘗試後,我終於明白了,我想與任何將來可能會遇到這個問題的人分享我的程式碼,或者以便我將來需要時可以找到它。我使用了 MS visual studios,所以請根據您的編譯器進行調整。
對於第一個問題,始終回答 3 或修改程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include "stdafx.h" //you may have to remove this depending on you compiler
#include <iostream>
using namespace std;
struct Pizza_Analysis //defining the struct
{
char company_name[35];
double dia_of_pizza;
double weight_of_pizza;
};
int main()
{
int num_of_companies;
//using new to allocate the structure
Pizza_Analysis *ps = new Pizza_Analysis[3];
cout << "How many companies do you want to look at? ";
cin >> num_of_companies;
cin.get();
//the struct array at work
for(int i=0; i<num_of_companies; i++)
{
cout << "\n\nPlease enter company name. ";
cin.getline(ps<i>.company_name,35);
cout <<"\n\nPlease enter the diameter of the pizza. ";
cin >> ps<i>.dia_of_pizza;
cout <<"\n\nPlease enter the weight of the pizza. ";
cin >> ps<i>.weight_of_pizza;
cin.get();
}
cout << endl << endl;
//the struct array at work
// prints the input to screen
for(int i=0; i<3; i++)
{
cout << "Company Name : " << ps<i>.company_name << endl
<< "diameter of pizza : " << ps<i>.dia_of_pizza << endl
<< "Weight of pizza : " << ps<i>.weight_of_pizza << endl <<endl;
};
delete [] ps;
system("pause");//you may have to remove this depending on you compiler
return 0;
}
|