+ 1

Why is my code not working?

For my code project, I am suppose to create a program that takes the ages of all 5 people as input, and outputs the total price of the tickets. A ticket costs $10 for 5 people (5*10=50). For example: Sample Input: 55 28 15 38 63 Sample Output: 42.5 So I would have to find the youngest age of the 5 people, and use it as their discount. So for this example, $50-15%=$42.5 Here is the code that I wrote: #include <iostream> #include <iomanip> using namespace std; int main() { int ages[5]; for (int i = 0; i < 5; ++i) { cin >> ages[i]; } //your code goes here int ticket = 10; double totalTicket = ticket * 5; double min = ages[0]; double total; for (int i = 0; i < 5; i++) { if (ages[i] < min) { min = ages[i]; } total -= totalTicket * min / 100 - totalTicket; cout << total << min; } return 0; } Can someone explain to me why it is not working?

24th Dec 2022, 5:31 AM
Gradi Maxime Kasita Mbatika
3 Answers
+ 3
Gradi Maxime Kasita Mbatika let the loop finish to get an accurate value for min, and then calculate and print total outside of the loop. Take note of Rivan's correction to your formula for total. Don't include min in the output, else Code Coach will reject it.
25th Dec 2022, 6:56 PM
Brian
Brian - avatar
+ 1
Firstly, you're not sorting the array properly. You're directly accessing the first element of the array without checking if it's the smallest or not. Also your for loop would print multiple values if they are smaller than the previous element. You should first sort the array using the sort function in C++ and then access the first element. Next the calculation that you're doing is wrong. You should use something like this: total = totalTicket - (totalTicket * min / 100); If you use the sort function then you can remove the for loop and directly use the above given code and then output it.
24th Dec 2022, 6:48 AM
Rivan
+ 1
Thanks you guys. It worked. 👍
2nd Jan 2023, 8:55 PM
Gradi Maxime Kasita Mbatika