+ 2

Ticket Office (Pro) - What am I doing wrong?

You are working on a ticketing system. A ticket costs $10. The office is running a discount campaign: each group of 5 people is getting a discount, which is determined by the age of the youngest person in the group. You need to create a program that takes the ages of all 5 people as input and outputs the total price of the tickets. Sample Input: 55 28 15 38 63 Sample Output: 42.5 The youngest age is 15, so the group gets a 15% discount from the total price, which is $50 - 15% = $42.5 The given code is declaring an array of 5 elements and taking them from input using a loop. #include <iostream> using namespace std; int main() { int ages[5]; for (int i = 0; i < 5; ++i) { cin >> ages[i]; } //your code goes here double ticketPrice = 10; double totalCost; double discount; int sizeofGroup = sizeof(ages) / sizeof(ages[0]); totalCost = sizeofGroup * ticketPrice; // cout << totalCost << endl; for (int i = 0; i < ages[i]; ++i) { discount = ages[0]; if (ages[i] < discount) { discount = ages[i]; } } cout << discount << endl; // Here to see the value of "discount" cout << totalCost - (totalCost * discount / 100); return 0; } Test Case 2 Input 69 48 33 25 29 Your Output 29 35.5 Expected Output 37.5

21st Feb 2021, 2:23 PM
Fredric Kearnes
Fredric Kearnes - avatar
3 Antworten
+ 3
In your *for* loop for (int i = 0; i < ages[i]; ++i) { discount = ages[0]; if (ages[i] < discount) { discount = ages[i]; } } 1) your loop will go beyond the size of the array leading to undefined behaviour 2) *discounts* is reset to ages[0] in the begining or every iteration Here is the fix👇 https://code.sololearn.com/czwfLueDzMPO/?ref=app
21st Feb 2021, 2:38 PM
Arsenic
Arsenic - avatar
+ 1
discount = ages[0]; // not in a loop for (int i = 0; i < 5; i++) { if (ages[i] < discount) { discount = ages[i]; } }
21st Feb 2021, 2:37 PM
Максим Белых
Максим Белых - avatar
+ 1
@Max thanks for the answer. @Arsenic thank you for the explanation.
21st Feb 2021, 2:58 PM
Fredric Kearnes
Fredric Kearnes - avatar