+ 2
Want help in Halloween candy
Hi guys actually I'm stuck in solving the Halloween candy problem. Can anybody help me out? In c++. #include <iostream> using namespace std; int main() { int houses; cin>>houses; int percentage; //your code goes here percentage = (houses/2)*100; if(houses>=3){ cout<<percentage; } return 0; } So guys that's my code.
13 Réponses
+ 5
There are some problems with your above code:
1. The formula you used to calculate the percentage of dollar bills is wrong (reversed).
2. By default, if you divide an integer by another integer in C++, the result will be an integer as well, e.g.
1 / 2 = 0
7 / 2 = 3
where the decimal part is cut off. If you expect a floating point number as result of a division, at least one of the operands must be a floating point value itself, e.g.
1 / 2.0 = 0.5
7.0 / 2 = 3.5
3. The task states to round the result up to the nearest integer. This can easily be achieved by including the <cmath> library and using std::ceil:
https://en.cppreference.com/w/cpp/numeric/math/ceil
And just so by the way: The description promises that the value of "houses" will always be at least equal to three, therefore the if-statement is unnecessary.
Try to incorporate all of these things into your solution.
+ 4
Shravan Mathapati , before we can help you, you should have done a try by yourself first. Please put your code in playground, save it there and then post the link to it here. Thanks!
+ 4
Shravan Mathapati Linking to the code coach problem itself will only show us our own codes, since you can not see the solutions of others. That is why Lothar instructed you to copy your code to a playground project and share that instead.
+ 3
It is better to see us your attempt first.
+ 3
std::round() rounds a decimal number either up or down, depending on its value, but the task states to always "round up to the nearest whole number". That is the reason I advised you to use std::ceil() earlier, as it will always round up.
Also, "percentage" will never be smaller or equal to zero, so the check is redundant, but it won't affect any of the test cases.
+ 2
Shadow thanks for your help
+ 2
Here's a simple python version. Not sure if it helps.
https://code.sololearn.com/cT112kPuS73X/?ref=app
+ 1
Shadow
this is my updated code ,but still it fails one case out of 5.
#include <cmath>
#include <iostream>
using namespace std;
int main() {
/*declaring all the variables*/
float houses;
cin>>houses;
float percentage;
/*getting the number of dollr bills*/
/*finding out the percentage */
percentage = (2/houses)*100;
/*rounding up to the nearest integer*/
percentage = round(percentage);
/*if the percentage comes 0 then*/
if(percentage<=0){
cout << percentage +1;
}
else{
cout<<percentage;
}
return 0;
}
what should be done
0
https://www.sololearn.com/coach/4?ref=app
Lothar here's my try
0
Here is my first attempt to solve this problem.
please help me out
0
Thank you guys .
I solved it with your help
0
How to put two login forms in a page