In: Computer Science
Use C language
Problem 1: Buy cheese (Level 1)
• Problem description
You have M dollors and want to buy as much cheese as possible.
There is a cheese shop with
two kinds of cheese. The unit prices of the both cheese are p1 and
p2, the total amount of them
are a1 and a2. You can buy either cheese or both, but the amount
you buy cannot exceed its total
amount. Write a program to output the largest amount of cheese you
can buy.
• Input & output requirements
All the integers variables (M, p1, a1, p2, and a2) are taken from
user input. The input begins
with a line containing one non-negative interger M, and followed by
two lines, each line
contains two integers, unit price and total amount.
The output should be a real number accurate up to 2 decimal
places.
• Sample results
Sample 1
Please input M: 2↲
Please input p1 and a1: 1 2↲
Please input p2 and a2: 2 2↲
The maximum amount of cheese is 2.00
Sample 2
Please input M: 3↲
Please input p1 and a1: 2 2↲
Please input p2 and a2: 1 1↲
The maximum amount of cheese is 2.00
Note:AS PER THE QUESTION THE ANSWER CAN BE FRACTIONAL/FLOAT ALSO.
EXAMPLE;
4
1 3
2 2
ANSWER IS 3.50.(3 items from 1st type and 0.5 items from second)
#include <stdio.h>
void main()
{
int a1,a2,p1,p2;
float dollars,ans;
scanf("%f",&dollars);
scanf("%d %d",&p1,&a1);
scanf("%d %d",&p2,&a2);
if(p1<p2) //will
consider lowest unit price first
{
while(a1 &&
dollars>=p1)
{
dollars=dollars-p1;
ans=ans+1;a1--;
}
if(a1>0) //still items
left
{
printf("%.2f",ans+dollars/p1);
return;
}
while(a2 &&
dollars>=p2) //if first type exhausted,will go for
next
{
dollars=dollars-p2;
ans=ans+1;a2--;
}
if(a2>0)
{
printf("%.2f",ans+dollars/p2);
return;
}
}
else //same process but
p1>=p2;either above or this part!!!
{
while(a2 &&
dollars>=p2)
{
dollars=dollars-p2;
ans=ans+1;a2--;
}
if(a2>0)
{
printf("%.2f",ans+dollars/p2);printf("secondYes");
return;
}
while(a1 &&
dollars>=p1)
{
dollars=dollars-p1;printf("Yes");
ans=ans+1;a1--;
}
if(a1>0)
{
printf("%.2f",ans+dollars/p1);
return;
}
}
printf("%.2f",ans);
return;
}