正在验证功能
Validating function
我的问题是如何验证getTestScore
函数的数据?需要程序在用户输入负数或超过100的数字时告诉用户invalid data, please enter a score in between 0 and 100
。谢谢
#include <iostream>
using namespace std;
//function prototypes
float getTestScore();
float calcAverage(float score1, float score2, float score3);
int main()
{
float s1, s2, s3; //these variables are used to store test scores
float average;
//call getTestScore function to get the test scores
s1 = getTestScore();
s2 = getTestScore();
s3 = getTestScore();
//call calcAverage to calculate the average of three test scores
average = calcAverage(s1, s2, s3);
//display the average
cout << "average of three test scores(" << s1 << "," << s2 << "," << s3 << ")is" << average << endl;
return 0;
}
//function definitions/implementation getTestScore function gets a test score from the user and
//validates the score to make sure the value is between 0 and 100. if score is out of range
//getTestScore function allows the user to re-enter the score. This function returns a valid score
// to the caller function
float getTestScore()
{
float score = 0;
do
{
cout << "Enter test score: " << endl;
cin >> score;
} while (!(score >= 0 && score <= 100));
return score;
}
// calcAverage function calculates and returns the average of the three test scores passed to
//the function as input.
float calcAverage(float score1, float score2, float score3)
{
float average;
average = (score1 + score2 + score3) / 3;
return average;
}
您可以将while循环更改为:
float getTestScore()
{
float score = 0;
while ((cout << "Enter test score: ")
&& (!(cin >> score) || score < 0 || score > 100)) {
// This part only gets executed on invalid input
cout << "invalid data, please enter a score in between 0 and 100 ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
return score;
}
通过使用"Do While",您在检查输入之前至少执行一次代码块。
因此,第一个输入不受您的条件检查:
while (!(score >= 0 && score <= 100));
使用标准while循环并因此在动手之前检查此条件应该可以解决您的问题。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 正在尝试了解输入验证循环
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中检查2D数组中负值的输入验证
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- LibGit2 SSH身份验证失败
- Vulkan验证层不断在VkQueuePresentKHR()上抛出图像布局错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- “并非所有控制路径都返回一个值./&quot“控制可能达到非空隙功能的末端”.验证时循环时
- CIN验证功能有时不会自动运行
- 如何跟踪LLVM验证功能错误"Expected no forward declarations!"?
- 正在验证功能
- 增强程序选项和验证功能