简体   繁体   中英

Can I put a range fo the user input on C++?

I need the user to input 7 numbers, they can't be smaller than 0 or bigger than 10. I'm aware I could do it with an IF or WHILE, but I'm not supposed to use them.

Here is my code (it gets the average of 7 scores with two decimals):

#include <iostream>
#include <iomanip> 
using namespace std;

int main(){
    float c1, c2, c3, c4, c5, c6, c7;
    float promedio = 0;

    cin>> c1 >> c2 >> c3 >> c4 >> c5 >> c6 >> c7;
    promedio = (c1+c2+c3+c4+c5+c6+c7)/7;
    cout<< setprecision(2) << promedio <<'\n';
}

You can try something like this.

main.cpp

#include <iostream>
#include <iomanip>
using namespace std;

double averageNumber(double num) {
    double average = 0;
    average = num/7;
    return average;
}

int main()
{
    double num, total;
    int i=0;

for(; i<7; i++) {
    cout << "Enter a number: " << endl;
    cin >> num;
    if(num>=0 && num<=10) {
        total+=num;
    } else {
        cout << "Number is invalid. Please try again!";
        return 0;
    }
}
 cout << "Total is: " << total << endl;
 cout << "Average is: "<< setprecision(2) << averageNumber(total);

}

I need the user to input 7 numbers, they can't be smaller than 0 or bigger than 10. I'm aware I could do it with an IF or WHILE, but I'm not supposed to use them.

Here is my code (it gets the average of 7 scores with two decimals):

#include <iostream>
#include <iomanip> 
using namespace std;

int main(){
    float c1, c2, c3, c4, c5, c6, c7;
    float promedio = 0;

    cin>> c1 >> c2 >> c3 >> c4 >> c5 >> c6 >> c7;
    promedio = (c1+c2+c3+c4+c5+c6+c7)/7;
    cout<< setprecision(2) << promedio <<'\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM