输入一个三位数,计算该数各位上的数字之和,如果在[1, 12]之内,则输出与数字之和相对应的月份的英文单词,否则输出***。要求:用指针数组记录各月份英文单词的首地址,且不得使用全局变量。目前仅完成了main函数和bizProcess函数,请编程实现hundredsDigit函数、tensDigit函数、unitsDigit函数、searchMonth函数和getNumber函数
时间: 2023-07-16 18:15:40 浏览: 146
好的,我来给您完成这个程序。首先是头文件和main函数的框架:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void bizProcess(int num);
void hundredsDigit(int num, int* hundreds);
void tensDigit(int num, int* tens);
void unitsDigit(int num, int* units);
int searchMonth(int sum, const char* monthName[]);
int getNumber();
int main() {
int num = getNumber();
bizProcess(num);
return 0;
}
```
接下来是hundredsDigit、tensDigit和unitsDigit函数的实现:
```c++
void hundredsDigit(int num, int* hundreds) {
*hundreds = num / 100;
}
void tensDigit(int num, int* tens) {
*tens = (num / 10) % 10;
}
void unitsDigit(int num, int* units) {
*units = num % 10;
}
```
然后是searchMonth函数,使用指针数组存储月份名称的首地址,并依次比较得到对应的月份名称:
```c++
int searchMonth(int sum, const char* monthName[]) {
if (sum >= 1 && sum <= 12) {
const char* month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for (int i = 0; i < 12; i++) {
if (i + 1 == sum) {
*monthName = month[i];
return 1;
}
}
}
return 0;
}
```
最后是getNumber函数,用于获取用户输入的三位数:
```c++
int getNumber() {
int num;
cout << "Please enter a three-digit number: ";
cin >> num;
while (num < 100 || num > 999) {
cout << "Invalid input, please enter a three-digit number: ";
cin >> num;
}
return num;
}
```
完整代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void bizProcess(int num);
void hundredsDigit(int num, int* hundreds);
void tensDigit(int num, int* tens);
void unitsDigit(int num, int* units);
int searchMonth(int sum, const char* monthName[]);
int getNumber();
int main() {
int num = getNumber();
bizProcess(num);
return 0;
}
void bizProcess(int num) {
int hundreds, tens, units;
const char* monthName;
hundredsDigit(num, &hundreds);
tensDigit(num, &tens);
unitsDigit(num, &units);
int sum = hundreds + tens + units;
if (searchMonth(sum, &monthName)) {
cout << "The month is " << monthName << endl;
} else {
cout << "***" << endl;
}
}
void hundredsDigit(int num, int* hundreds) {
*hundreds = num / 100;
}
void tensDigit(int num, int* tens) {
*tens = (num / 10) % 10;
}
void unitsDigit(int num, int* units) {
*units = num % 10;
}
int searchMonth(int sum, const char* monthName[]) {
if (sum >= 1 && sum <= 12) {
const char* month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
for (int i = 0; i < 12; i++) {
if (i + 1 == sum) {
*monthName = month[i];
return 1;
}
}
}
return 0;
}
int getNumber() {
int num;
cout << "Please enter a three-digit number: ";
cin >> num;
while (num < 100 || num > 999) {
cout << "Invalid input, please enter a three-digit number: ";
cin >> num;
}
return num;
}
```
阅读全文