以下是我的代码,显示每位卖家的平均售价。无论我输入的盒子数量或卖家数量如何,我总是得到3。
#include <iostream>
using namespace std;
int main()
{
int numBoxes, // Number of boxes of cookies sold by one child
totalBoxes = 0, // Accumulator - Accumulates total boxes sold by the entire troop
numSeller = 1; // Counter - Counts the number of children selling cookies
double averageBoxes; // Average number of boxes sold per child
cout << " **** Cookie Sales Information **** \n\n";
// Get the first input
cout << "Enter number of boxes of cookies sold by seller " << numSeller
<< " (or -1 to quit): ";
cin >> numBoxes;
while (numBoxes != -1)
{
cout << "Please input the number of boxes sold by the next seller (or -1 to quit): ";
cin >> numBoxes;
totalBoxes += numBoxes; // Accumulates the running total
numSeller++;
}
numSeller = numSeller - 1;
// WHEN THE LOOP IS EXITED, THE VALUE STORED IN THE numSeller COUNTER
// WILL BE ONE MORE THAN THE ACTUAL NUMBER OF SELLERS. SO WRITE CODE
// TO ADJUST IT TO THE ACTUAL NUMBER OF SELLERS.
if (numSeller == 0)
cout << "\nNo boxes were sold.\n\n";
else
{
averageBoxes = (totalBoxes / numSeller);
cout << "\n\nThe average number of boxes sold per seller is: " << averageBoxes << endl;
}
return 0;
}
答案 0 :(得分:1)
您遇到两个问题:
numBoxes
中存储的第一个值,因此会丢失数据。以下是关于整数除法的一些重要事项。
Division in C++ not working as expected
What is the behavior of integer division?
Dividing two integers to produce a float result
C++ Best way to get integer division and remainder
这是固定代码。只需要两个单线修复。
代码清单
#include <iostream>
using namespace std;
int main()
{
int numBoxes, // Number of boxes of cookies sold by one child
totalBoxes = 0, // Accumulator - Accumulates total boxes sold by the entire troop
numSeller = 1; // Counter - Counts the number of children selling cookies
double averageBoxes; // Average number of boxes sold per child
cout << " **** Cookie Sales Information **** \n\n";
// Get the first input
cout << "Enter number of boxes of cookies sold by seller " << numSeller
<< " (or -1 to quit): ";
cin >> numBoxes;
totalBoxes += numBoxes;
while (numBoxes != -1)
{
cout << "Please input the number of boxes sold by the next seller (or -1 to quit): ";
cin >> numBoxes;
totalBoxes += numBoxes; // Accumulates the running total
numSeller++;
}
numSeller--;
// WHEN THE LOOP IS EXITED, THE VALUE STORED IN THE numSeller COUNTER
// WILL BE ONE MORE THAN THE ACTUAL NUMBER OF SELLERS. SO WRITE CODE
// TO ADJUST IT TO THE ACTUAL NUMBER OF SELLERS.
if (numSeller == 0)
cout << "\nNo boxes were sold.\n\n";
else
{
averageBoxes = ((double)totalBoxes / (double)numSeller);
cout << "\n\nThe average number of boxes sold per seller is: " << averageBoxes << endl;
}
return 0;
}