+ 1

Ticket Office C++ Problem

So I'm in the middle of the Ticket Office problem in C++, and I'm having trouble figuring out where I've gone wrong. Here's the premise of the problem: 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 My code works just fine for test cases 1 and 3, but it runs into a weird problem where it just skips over a number for test case 2. Here's my code for reference: #include <iostream> using namespace std; int main() { int ages[5]; for (int i = 0; i < 5; ++i) { cin >> ages[i]; } //your code goes here float youngest = ages[0]; float discount = youngest/100; for (int j = 0; j < 5; j++){ if(youngest > ages[j+1]){ youngest = ages[j]; } } float total = 50-(50*discount); cout << total; return 0; }

23rd Dec 2021, 3:06 PM
ThePanPixel
4 Answers
+ 3
Hmm, i guess you should check which one is the youngest before calculating discount. And i recommend you to do calculations on floats (writing 100.0 instead of 100 etc.) Idk if it is really needed, but it is probably a good habit while working On floats. And why do you check ages[j+1]? Use just "j", indexing start from 0 to n-1, where n is the number of elements in the array, so your for loop is reading some random memory, which causes errors. Change the condition to j<4, or check ages[j] in the if statement
23rd Dec 2021, 3:24 PM
Michal Doruch
+ 3
The problem is, that you did not update your "discount" variable. You can use a pointer if u want. I got ya. #include <iostream> int main(int argc, char**argv) { int people[5]; int* smallest = &people[0];// youngest person, // smallest in age. // the pointer will be updated, // no need to copy values // repeatedly for(int i=0; i<5; i++){ std::cin >> people[i]; if(people[i] < *smallest) smallest = &people[i]; } const float total = 50 - (0.5 * (*smallest)); std::cout << total; // hooray (: return 0; }
23rd Dec 2021, 7:10 PM
Purple Requiem
Purple Requiem - avatar
+ 1
// try this int youngest = ages[0]; for (int i=1; i<5; i++) if(youngest > ages[i]) youngest = ages[i]; float total = 50-(.5*youngest); cout << total;
23rd Dec 2021, 3:45 PM
SoloProg
SoloProg - avatar
+ 1
The discount variable was absolutely the problem. Thanks to y’all for your help!
23rd Dec 2021, 7:56 PM
ThePanPixel