-1

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';
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Well, you can rewrite a `while` loop into an equivalent `for` loop. But if you're so restricted as to be unable to use `if` and `while`, you might need to talk with your instructor about what you _are_ allowed to use. – Nathan Pierson Jan 25 '21 at 02:48
  • 2
    This reads like it came from a contest/challenge/competitive coding/hacking site. Is it? If your goal is to learn C++, you won't learn anything there. In nearly all cases, like this one, the correct solution is based on a mathematical or a programming trick. If you're trying to learn C++, you won't learn anything from meaningless online contest sites [but only from a good C++ textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Sam Varshavchik Jan 25 '21 at 02:49
  • 1
    The only reason I can see for an assignment like this, is to make you see how hard life would be without loops or arrays etc. – Some programmer dude Jan 25 '21 at 02:58
  • So, are you meant to ask the user to reenter the ones that don't fit in the range (which would require either a for loop, a while loop, or an if statement) or can you just clamp the values to the range so that anything smaller than 0 becomes 0 and anything larger than 10 becomes 10? – Jerry Jeremiah Jan 25 '21 at 03:47
  • If you are allowed to clamp the values: `c1 = c1*(c1>=0.); c1 = c1*(c1<=10.) + 10.*(c1>10.);` Here is a test program: https://onlinegdb.com/S1l5y-aikO – Jerry Jeremiah Jan 25 '21 at 03:54
  • Thanks everyone! It is from a site that “trains you” for a competence is called OmegaUp, I talked to my instructor and he told it was a troll problem, meaning I can actually use if and while :( – Priscila Molina Reza Jan 26 '21 at 04:58

1 Answers1

0

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);

}
TechGeek49
  • 476
  • 1
  • 7
  • 24