0

== Code founded online in Chegg, however the output is not the one that was told. It supposed to give a ounce_left of 4, but is giving an 8.

Someone knows where is the bug?

==

In this problem, our task is to find the no_of _cans needed and the no_of_ounce left over.

The formula to calculate no_of_cans needed is: ceil(amount/12).

Formula to calculate no_of_ounce needed is: 12*ceil(amount/12)-amount.

Algorithm

  1. Take input amount from user.
  2. Divide amount/12 and store ceil of quotient in variable cans_needed.
  3. Ounce_left will be calculated as 12*cans_needed-amount.
  4. Print cans_needed.
  5. Print ounce_left.
  6. Stop.

Now let us try to implement the above algorithm using C++.

//header files used
#include<bits/stdc++.h>
using namespace std;

int main()
{
        int amount;
        //taking input from user
        cout<<"Enter Amount in ounces:";
        cin>>amount;
        
        //finding no of cans needed 
        //if it is evenly divided by 12 then ceil(quotient)=quotient 
        //else ceil(quotient)=quotient+1
        
        int cans_needed=ceil((double)amount/12);
        
        //finding ounce_left
        int ounce_left=amount%12;
        
        cout<<"Cans Needed :"<<cans_needed<<endl; //printing cans_needed
        
        cout<<"Ounce left: "<<ounce_left<<endl;  //printing ounce_left
        
        
}
  • I really struggle to think about which of those is harder, to fun with C++ or to learn algorithm. I sort of failed with both.... – user3528438 Sep 10 '21 at 01:51
  • 1
    Can you explain, exactly, why you believe that "It supposed to give a ounce_left of 4"? Where does it say that? In any case, this is a very typical example of low quality code found on those useless online coding competition sites: non standard C++ headers, lack of fundamental understand of why floating point math is not a replacement for proper integer math, and other issues. You will find that [a good C++ textbook](https://stackoverflow.com/questions/388242/) will be far easier to understand, and every example in it will have a detailed explanation, unless random code off a random web site. – Sam Varshavchik Sep 10 '21 at 01:55
  • what is the input? – bolov Sep 10 '21 at 01:55
  • Could you give an example walkthrough of your code to demonstrate why it should work? After each line of code, tell us the new value of the variable whose value changed (show your work for the arithmetic expressions). After walking through your code, walk through the given algorithm. At what point do these values differ from what your code produced? – JaMiT Sep 10 '21 at 02:06
  • 3
    You didn't do step 3 in the algorithm. There is no code that calculates `12*cans_needed-amount` – user3386109 Sep 10 '21 at 02:10

0 Answers0