0
#include <iostream>
using namespace std;
void main()
{
int numDays;
double sum = 0;
double avg;
cout << "Enter the number of days of sales";
cin >> numDays;
double *Sales = new double[numDays];
for (int i = 0; i < numDays; i++)
{
cout << "enter how much you sold for day " << i << endl;
cin>>*Sales;
sum = sum + *Sales;
cout << Sales;
}
delete[] Sales;
avg = sum/(numDays);
cout << "the sum is" << sum << endl;
cout << "the avg is" << avg << endl;
}
嗨,這是我得到的輸出可以somone解釋爲什麼指針不需要增加?以及用指針完成相同任務的正確方法。數組指針動態C++
Enter the number of days of sales2
enter how much you sold for day 0
1
0050CD70enter how much you sold for day 1
2
0050CD70the sum is3
the avg is1.5
Press any key to continue . . .
嘿,但爲什麼cin >> *(p ++);這不會去索引1? – CanyoucSharp
每次執行'*(p ++)'時,'p'遞增以指向'Sales'中的下一個存儲器地址。如果''(p ++)'爲'i'天,那麼''銷售''中有'i'條目。這給了我們一個「不變的」銷售 - p == i,一個在寫入的代碼片段中總是爲真的等式。但是在閱讀其他人的代碼時,指針有點難以遵循。所以我只是推薦你使用'Sales [i]'語法。 –
非常感謝! – CanyoucSharp