【发布时间】:2018-03-28 05:09:54
【问题描述】:
我想创建一个程序,询问用户年、月和日。它使用一个 void 函数根据设定的标准检查每个值,以针对设定的范围执行验证。例如。年份必须是 > 1970 和
同样的函数也用于验证月份和日期范围。
我刚刚开始这一年,但在将值传递给函数时遇到了麻烦。
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
//declare function
void get_data();
int main()
{
//local variable declaration
int input;
int criteria_1 = 1970;
int criteria_2 = 2020;
// ask for input and store
cout << "Enter the year: ";
cin >> input;
//call the function to validate the number
get_data(input, criteria_1, criteria_2);
return 0;
}
//define function
void get_data(int x, int y, int z)
{
// set variable for what is being inputted
int input;
//repeat asking user for input until a valid value is entered
while (x <= y||x >= z){
cout << "The valid range is >=" + y;
cin >> x;
input = x;
}
//display output on screen
cout << input << endl;
//reset variable for what was inputted
input = 0;
return;
}
你能给我一些指导吗?我对此很陌生。谢谢。
【问题讨论】:
-
你不需要在函数返回时“重置”局部变量——每个函数调用都有自己的。