簡體   English   中英

結構 + 函數代碼中斷

[英]struct + functions code breaks

代碼有問題,我找不到。 我被要求編寫一個貨幣結構並使用函數來操作它。 但該代碼不適用於任何功能。 我嘗試了 structers 數組,結果很好,對於任何缺少的信息,請發表評論,我會盡快回復。

錢.txt

2

12 20

13 40

 #include <iostream> #include <fstream> using namespace std; struct Money { //declaring structure int dollars; int cents; }; Money addMoney(Money *p[], int n) { //adds money data Money cash{ 0,0 }; int i; for (int j = 0; j < n; j++) { cash.dollars = cash.dollars + p[j]->dollars; cash.cents = cash.cents + p[j]->cents; } if (cash.cents >= 100) //100cents = 1 dollar { i = (cash.cents) / 100; cash.dollars = cash.dollars + i; i = (cash.cents) % 100; cash.cents = i; } return cash; } void printMoney(Money *p[], int n) { //printing money data for (int i = 0; i < n; i++) { cout << "Dollars: " << p[i]->dollars << endl; cout << "Cents: " << p[i]->cents << endl; } } Money maxMoney(Money *p[], int n) { Money cash; cash.dollars = p[0]->dollars; cash.cents = p[0]->cents; for (int i = 0; i < n; i++) { if ((p[i]->dollars)>=(cash.dollars)) if ((p[i]->cents)>(cash.cents)) { cash.dollars = p[i]->dollars; cash.cents = p[i]->cents; } } return cash; } void main() { Money cash; ifstream mycin("money.txt"); if (mycin.fail()) cout << "Enable to open file"; int x; mycin >> x; Money *arr = new Money[x]; for (int i = 0; i < x; i++) { mycin >> arr[i].dollars; mycin >> arr[i].cents; } cout << "The values in money.txt are: "; printMoney(&arr, x); cash = addMoney(&arr, x); cout << "These values added are :"; cout << cash.dollars << " Dollars and " << cash.cents << " cents" << endl; cash = maxMoney(&arr, x); cout << "Maximum value is :"; cout << cash.dollars << " Dollars and " << cash.cents << " cents" << endl; }

這些函數似乎接受指向Money 的指針數組,但您正試圖將它們與 Money 數組一起使用。

我建議您使用指向更簡單類型(如int )的指針數組,直到您對這個概念感到滿意,然后再嘗試使用 Money。

這聽起來很像家庭作業,所以我不會發布完整的解決方案,但我會解釋似乎是誤解的內容並給你一些指示。

首先,您將數據結構聲明為 Money 結構數組,例如,包含 Money 結構的一系列連續內存塊,主程序中的“arr”指向第一個。

但是,在程序的其余部分(函數)中,您似乎希望使用的數據結構是 Money指針數組。 看到不同? 它們不一樣,這不會按原樣工作。 你必須保持一致。

要么你正在處理一個結構數組,在這種情況下,你將一個簡單的 Money* 有效地傳遞給你的函數無處不在(並且你用 . 而不是 -> 取消引用)

或者您正在處理一個指針數組,在這種情況下,您可以有效地傳遞一個指向 (Money 指針) 的指針,然后像您所做的那樣使用 -> 取消引用。 但是,當您在主程序中讀取它們時,您還必須單獨分配每個 Money 結構。 也就是說,為指針數組分配內存不會自動為指針數組中的每個 Money 指針引用分配內存,因此您需要為正在讀取的每個條目執行此操作。

因此,正如您現在應該意識到的那樣,有多種方法可以修復您的程序。

根據您后來的評論,鑒於函數簽名需要保持原樣,我建議您使用 Money 指針數組。

Money** arr = new Money*[x]

然后你需要在閱讀過程中在循環中添加一行,以實際使每個 Money * 指向一個 Money 結構:

for (int i = 0; i < x; i++)
{
    arr[i] = new Money
    ...

最后,因為“arr”現在是指向 Money 的指針,您可以直接將其傳遞給您的函數,因此調用它們只是例如:

printMoney(arr, x);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM