【发布时间】:2019-07-13 06:34:34
【问题描述】:
我应该使用字符串数组来输出“输入降雨量为 x”行,x 是月份的名称,并将输入发送到单独的数组进行计算。目前,当我运行我的代码时,我看到“输入 1 的降雨量”、“输入 2 的降雨量”等,而不是“输入 1 月的降雨量”、“输入 2 月的降雨量”。除此之外,代码还需要显示总降雨量、平均降雨量以及最低和最高月份的降雨量。我可以让程序输出正确的总数和平均值,但是,最高和最低月份只输出一个随机数而不是月份名称。
我试图创建原型并将数组调用到函数中,但我认为问题可能是由于我的字符串数组存在问题。我试过使用 for 循环,我试过改变我的语法无济于事。我目前在调试过程中没有收到任何错误,只看到不正确的输出而不是字符串输出。
#include <iostream>
#include <string>
using namespace std;
// Function Prototypes
void getMonthlyRainfall(double[], int);
double getTotal(const double[], int);
double getHighestAmount(const double[], int);
double getLowestAmount(const double[], int);
int main()
{
const int MONTHS = 12;
string monthNames[MONTHS] = { "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November",
"December" };
double rainfall[MONTHS], // Array
total,
average,
lowestAmount,
highestAmount;
//Get rainfall input from user
getMonthlyRainfall(rainfall, MONTHS);
// Get the total amount of rain for the year
total = getTotal(rainfall, MONTHS);
// Get the average rainfall
average = total / MONTHS;
// Get the month with the lowest rainfall
lowestAmount = getLowestAmount(rainfall, MONTHS);
// Get the month with the highest rainfall
highestAmount = getHighestAmount(rainfall, MONTHS);
cout << "Total rainfall: " << total << endl;
cout << "Average rainfall: " << average << endl;
cout << "Least rainfall in: " << getLowestAmount << endl;
cout << "Most rainfall in: " << getHighestAmount << endl;
return 0;
}
void getMonthlyRainfall(double rain[], int size)
{
int index;
for (index = 0; index < 12; index++)
{
cout << "Enter rainfall for " << (index + 1) << ": ";
cin >> rain[index];
}
}
double getTotal(const double numbers[], int size)
{
double total = 0; // Accumulator
for (int count = 0; count < size; count++)
total += numbers[count];
return total;
}
double getHighestAmount(const double numbers[], int size)
{
double highest; // Holds highest value
// Get array's first element
highest = numbers[0];
// Step through array
for (int count = 0; count < size; count++)
{
if (numbers[count] > highest)
highest = numbers[count];
}
return highest;
}
double getLowestAmount(const double numbers[], int size)
{
double lowest; // Holds lowest value
// Get array's first element
lowest = numbers[0];
// Step through array
for (int count = 0; count < size; count++)
{
if (numbers[count] < lowest)
lowest = numbers[count];
}
return lowest;
}
正如我所说,第一个输出应该是一个月的实际名称,并且应该是有序的。例如,提示应该首先要求用户输入一月份的总降雨量,用户输入一个数字。然后提示继续要求用户输入 2 月的数字,依此类推,直到 12 月。相反,我看到提示要求用户输入“1”的总降雨量,用户输入一个数字,然后提示要求用户输入“2”的降雨量,直到它达到 12。程序进行计算并输出正确的总降雨量和平均值,但是当它应该输出“降雨量最高(或最低)的月份:(月份名称)”时,它会给我一个随机数,例如 01201686。
总而言之,字符串数组输出月份名称,用户输入存储在单独的数组中进行计算。这些计算是针对总计和平均值输出的,但降雨总量需要与相应实体的月份进行比较,并且最高和最低的输出需要是字符串而不是数字。
【问题讨论】:
-
编译时不要忽略编译器警告。编译器警告是编译器告诉你,虽然代码在语法上是正确的,但它可以编译,但它可能在逻辑上不正确,并且会崩溃、行为不端甚至看起来像它的行为一样直到突然不正确。
-
我想推荐:请不要使用普通的 C 样式数组。请尝试使用 STL 容器。