c++ - 验证功能

标签 c++ testing

我的问题是如何验证 getTestScore 函数的数据?需要程序告诉用户无效数据,请输入一个介于 0 和 100 之间的分数,以防他们输入负数或超过 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;
}

关于c++ - 验证功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111291/

相关文章:

java - JUnit 与 TestNG

c++ - 难以理解 C++ 指针语法

c++ - g++ "is not a type"错误

c++ - 我可以重新定义 C++ 宏然后重新定义它吗?

c++ - 通过调用 super 改变类变量

java - Unitils 项目还活着吗?

c++ - 迭代器跳过循环

javascript - 使用 Protractor 双击在 chrome 中工作正常但在 firefox 中不起作用

java - 在我的 Java 应用程序中测试 SMTP 错误

ios - 是否有类似 Android 上的 Monkey 的 iOS UI Exerciser?