So I've searched the forums a bit and tried to find a solution to my problem without success. I've been trying to do some text exercises from an old test in my programming course in preparation for an upcoming exam. The link to the test can be found here:
The exercise in question is the second with a beautiful looking mathematical formula. Anyway, I'm having trouble with the part where it should check to make sure the input is greater than zero as my array will always have a zero in any of the spaces I haven't filled up. I'm supposed to be using arrays in this particular exercise. Here is the code I've written so far:
#include <iostream>
#include <iomanip>
usingnamespace std;
int a=0;
int mult(int S[], int a);
int add(int S[], int a);
int sort(int S[], int a);
int main()
{
cout << "Sequence: ";
int X[100]={};
for (int i=0; i<100; i++){
cin >> X[i];
if (isdigit(X[i]))
break;
if(X[i]<=0)
do{
cout << "Numbers in the sequence must be greater than 0! \nTry again: ";
cin >> X[i];
} while (X[i]==0); //this particular do-while loop will run once and then never ask for an input. I really just need to make sure a number that's been input is over zero. The sequence should stop once the user enters anything other than a number.
if (X[i]!=0)
a++;
}
int S[a];
for(int j=0;j<a;j++){
S[j] = X[j];
}
double Ep, Pi, result;
S[a] = sort(S,a);
Ep=add(S,a);
Pi=mult(S,a);
result = ((S[a-2]*Pi)-(S[a-1]*Ep))/(a*(a-1));
cout << fixed << setprecision(3) << "Result: " << result;
}
int mult(int S[], int a){
int prod = 1;
for (int i=0; i<a; i++){
prod *= S[i];
}
return prod;
}
int add(int S[], int a){
int sum = 0;
for (int i=0; i<a; i++){
sum += S[i];
}
return sum;
}
int sort(int S[], int a){
int temp;
for (int pass = 0; pass <= (a - 2); pass++) {
for (int i = 0; i < (a - 1); i++) {
if (S[i] > S[i + 1]) {
temp = S[i];
S[i] = S[i + 1];
S[i + 1] = temp;
}
}
}
return S[a];
}
well i guess i made a change before i posted it to the forum but the values of all the numbers in the sequence must be greater than zero. So both negative numbers and zero are disallowed. Sorry for the confusion...