user15325072
user15325072

Reputation:

is there a way to fix this problem I have been having with multiple conditions?

#include <iostream>
using namespace std;

int main() {
    int ages[5];

    for (int i = 0; i < 5; ++i) {
        cin >> ages[i];
    }
    
    int age_1 = ages[0];
    int age_2 = ages[1];
    int age_3 = ages[2];
    int age_4 = ages[3];
    int age_5 = ages[4];
    
    if (age_1 < age_2 and age_3 and age_4 and age_5) {
        
        float dis_1 = age_1 * 0.01;
        float dis_2 = 50 * dis_1;
        float dis_3 = 50 - dis_2;
        cout << dis_3 << endl;
    }
    else if (age_2 < age_1 and age_3 and age_4 and age_5) {
        
        float dis_1 = age_2 * 0.01;
        float dis_2 = 50 * dis_1;
        float dis_3 = 50 - dis_2;
        cout << dis_3 << endl;
    }
    else if (age_3 < age_1 and age_2 and age_4 and age_5) {
        
        float dis_1 = age_3 * 0.01;
        float dis_2 = 50 * dis_1;
        float dis_3 = 50 - dis_2;
        cout << dis_3 << endl;
    }
    else if (age_4 < age_1 and age_2 and age_3 and age_5) {
        
        float dis_1 = age_4 * 0.01;
        float dis_2 = 50 * dis_1;
        float dis_3 = 50 - dis_2;
        cout << dis_3 << endl;
    }
    else if (age_5 < age_4 and age_3 and age_2 and age_1) {
        
        float dis_1 = age_5 * 0.01;
        float dis_2 = 50 * dis_1;
        float dis_3 = 50 - dis_2;
        cout << dis_3 << endl;
    }else {
        cout << "50" << endl;
    } 
    
    
    return 0;
}

This is a code to get discounts based of the array. Whenever the smallest number is not the first put in, I get a different answer than I should.

Sample input:

69
48
33
25 
29

Expected output:

37.5

Actual output:

26 

Upvotes: 0

Views: 63

Answers (2)

Mukund Gohil
Mukund Gohil

Reputation: 3

You have used 'and' not properly. That is why the condition is not working. Try to get smallest element using a function as below:

#include <iostream>

using namespace std;

void displayDiscount(int age){
    float dis_1 = age * 0.01;
    float dis_2 = 50 * dis_1;
    float dis_3 = 50 - dis_2;
    cout << "Result: " << dis_3 << endl;
}

int getMin(int arr[], int n)
{
    int res = arr[0];
    for (int i = 1; i < n; i++)
        res = min(res, arr[i]);
    return res;
}

int main() { 
    int ages[5];
    
    for (int i = 0; i < 5; ++i) {
        cin >> ages[i];
    }
    
    int minAge = getMin(ages, 5); // size of array
    displayDiscount(minAge);
    
    return 0;
}

Upvotes: 0

Philip Nelson
Philip Nelson

Reputation: 1231

You need to write the if statement like this:

if (age_1 < age_2 and age_1 < age_3 and age_1 < age_4 and age_1 < age_5)

however this approach quickly becomes unmanageable with more values in the array.

You could look at std::min_element for finding the smallest element in an array

Upvotes: 1

Related Questions