# Day 2: Operators

# Day 2: Operators

Iven_Delacroix + 15 comments Note that JavaScript code snippet is broken, it tryes read data twice (once on hardcoded pard, once on "softcoded"), also it has 2 nested main() functions (which is the reason why output made in inner main() does not work).

To make it work student has to delete everything that is not hardcoded and use arguments "mealCost", "tipPercent" and "taxPercent" in the calculation (do NOT try to readLine() or something, all the data is already read in the hardcoded part).

kazeisc + 0 comments life saver. I thought the code looked really odd.

aloksaldanha + 0 comments They should really fix this!

LexDefoe + 0 comments I thought I was going crazy!

jadisvara + 0 comments Thank you!

jjsevinga + 0 comments Thanks :) Kinda sucks for a beginner. I banged my head against the table for nothing. Kidding but its kinde screwed.

wilsonsf1 + 0 comments Still broken, Thank you!

robby_widyahart1 + 0 comments Thank you

melissaintrees + 0 comments so when it says please ignore above this line...actually do the opposite. lol. Please fix this for us JS folks! :)

ynotravid + 0 comments This is so bad.

alexanderhusky + 1 comment Thank you so much! I was starting to get VERY frustrated and concerned that I couldn't do basic math!

rohit_v07 + 0 comments Hahahaha

beshur + 0 comments Fixed - they changed the initial code.

obscuredev312 + 3 comments I dont think there is need for this. The code works just fine in JS.

Remeber to use Math.floor() and Math.ceil() functions. If the decimal is >0.5 use floor, else ceil

Iven_Delacroix + 0 comments Comment just above is "Fixed - they changed the initial code", so I'm pretty sure for now it works just fine :)

shadamhb + 0 comments Thank you

EvilTomato + 0 comments I think using Math.round() would be much easier than using if statements.

luigi + 5 comments For the JavaScript code snippet to work, change the line

from

`solve(meal_cost, tip_percent, tax_percent);`

to

`console.log(solve(meal_cost, tip_percent, tax_percent));`

jonesjosh41 + 6 comments Don't overthink it....

// Complete the solve function below. function solve(meal_cost, tip_percent, tax_percent) { const tip = meal_cost * tip_percent / 100; const tax = meal_cost * tax_percent / 100; const total = Math.round(meal_cost + tip + tax) console.log(total); }

nupursingh775 + 1 comment its not working mine code was same but that also didn't run

please give correct solution

jonesjosh41 + 2 comments works for me. make sure you have javascript (nodejs) checked.

nupursingh775 + 0 comments ya i checked it and i got answer :)

justice_theledi + 0 comments Javascript(Nodejs) checked and No errors. Nice calculations/arithmetic.

bc140201192 + 0 comments that's giving an error

sachinkulkarni + 0 comments [deleted]sachinkulkarni + 0 comments works!!!!!!!!!!!!!!!

beatrizkah + 0 comments I raplaced all const to double and "console.log(total)" to Console.Writeline(total); then my code runs :)

AlexMo + 0 comments Frankly this is the best answer!

mahya_sadeghi + 0 comments Yes! Thank you!

yriquelme + 0 comments Great thanks!!!!!, you saved my life!!!!

Dillorom + 0 comments Thanks!

eselah + 0 comments This did it for me! Thanks buddy

davidn199 + 0 comments It is fixed now, but you also need to

`console.log`

the answer instead of`return`

ing it. They make an easy problem more complicated.coder_aky + 6 comments # Python 3 one liner :-)

print(round (float(input())*(1+int(input())*.01+int(input())*.01)))

arsh_suri + 0 comments [deleted]vsk1192 + 1 comment Can you explain your logic

zimmah + 1 comment It's basically

meal_price * (1 + tip_percent / 100 + tax_percent / 100)

you could do it like this too

print(round (float(input())*(1+(int(input())+int(input()))/100)))

rocketbot115 + 1 comment why add the one?

zimmah + 1 comment Because you want to include the meal price in the calculation.

Let's say you have a meal of $50 and you add 10% tip and 20% tax, if you'd do

meal * (tip_percent / 100 + tax_percent / 100)

you'd only get $15, so you add the 1 to include the meal itself.

sdberryman + 1 comment I've always been told that calculations should not be included in print statements, as unexpected things can happen (sequence of events isn't always as expected, etc). Is that just an unnecessary fear, or a good rule of thumb?

christianrhodes1 + 0 comments I think it's both. I do it for debugging purposes. Plus, it makes for good clean code

Akshat27 + 0 comments [deleted]pravati07 + 0 comments I get a TypeError when I run the code in Jupyter Notebook. Can you please explain?

TypeError Traceback (most recent call last) in ----> 1 print(round(float(input() * (1 + int(input()) * 0.1 + int(input())* 0.1))))

TypeError: can't multiply sequence by non-int of type 'float'

hp_well + 0 comments print(round(meal_cost * (1 + (tip_percent + tax_percent) / 100)))

ThatCoder + 10 comments I was able to finish but I'm curious.

dMealCost * nTipPercent/100;

Why is:

dMealCost * (nTipPercent/100);

correct and the following wrong even if the second is done separately and stored through a double?

AllisonP + 68 comments In short, this is due to order of operations (PEMDAS). The operation inside the parentheses is evaluated first, and then it is multiplied with

`dMealCost`

.

`nTipPercent`

is an**int**and`100`

is an**int**, and enclosing them in parentheses means that their result will be calculated first. The result of**int / int = int**; because a % is a fraction < 1, the result evaluates to**0**in integer division (so you're basically multiplying`dMealCost * 0`

). If you change`100`

to`100.0`

, it will evaluate as a double.ThatCoder + 1 comment Thank You.

pavaniv + 1 comment Thank you

qhm0527 + 2 comments Thanks a lot.

Anonymous_1998 + 1 comment [deleted]dharmendra_devr1 + 0 comments thank you

celik55 + 1 comment thanks

Chaitali25 + 1 comment thanks

adarsh0251 + 1 comment Thank you so much dear !!

ybandar1902 + 2 comments Mighty be a bit late but an example

mealCost*((double)tipPercent/100);

laxmanchhetri121 + 1 comment Thak you.

19kadem_hassan + 1 comment thanks

19kadem_hassan + 1 comment fam

n_p_dike + 0 comments gracias

prysa18 + 0 comments This does not work. You cannot typecast an integer to a double

Rakshitha_30 + 1 comment I had the same confusion and still not very clear. Can u help me understand it.

ayushm796 + 12 comments when you use '/'(divide operator) it returns you the quotient.For eg: when you write (20/100) the quotient is 0. Therefore you need to write 12*20/100 that gives you 240/100 = 2.40 ....... (12 is mealCost and 20 is tipPercent)

Rakshitha_30 + 0 comments Thanku :)

VD_hacker + 0 comments Thanx... Helped me :)

misterjsharp + 3 comments So I was running into this EXACT same problem, I changed the int variables they gave is into double and that resolved the issue as well.

1chetantamboli + 5 comments Try this

cout<<"The total meal cost is "<<round(meal*(1+0.01*(tip+tax)))<<" dollars.";

Dilip_Rathore + 0 comments Thank you bro

ssaulakh2 + 0 comments This doesn't work!

Sirius19 + 0 comments [deleted]pandeyshweta976 + 0 comments how you calculated 1 + .01?

shubhamnarlawar1 + 0 comments Why 1+ in your cout? Can you explain?

mmbore81 + 0 comments doesn't work

lovekumar2017 + 2 comments # !/bin/python3

import math import os import random import re import sys

# Complete the solve function below.

def solve(meal_cost, tip_percent, tax_percent): tip=float(meal_cost*(tip_percent/100)) tax=float(meal_cost*(tax_percent/100)) tc=float(meal_cost+tip+tax) print(round(tc)) if

**name**== '**main**': meal_cost = float(input())`tip_percent = int(input()) tax_percent = int(input())`

solve(meal_cost, tip_percent, tax_percent)

balavemulakonda + 0 comments can u plz explain this?

[deleted] + 0 comments it does not work!

asatyedev + 0 comments thank you

Jashin + 0 comments 240/100 != 2.40 // cz int/int=int its actually 12.00*20/100 240.00/100 == 2.40

sreeshu17 + 0 comments thank u sir.. i was facing such probs.. clarified after reading yours.

thinker1729 + 0 comments thanks

shadabgada234 + 0 comments thank you sir !

Raktimroy752 + 1 comment Tax=(mealcost*taxp)/100 is these statement is correct or not...

mirna_alkhoreby + 3 comments //yes it's correct, here is my all methods:

public double tip(){

`return (tipPercent * mealCost)/100; } public double tax(){ return (taxPercent * mealCost)/100; } public double total(){ return mealCost + tip() + tax(); }`

public double roundedTotal (){

`return Math.round(total()); }`

//but as I said the answer is 15.00 I want it to be 15 (in an integer form )

mirna_alkhoreby + 6 comments I decided to delete the methods & start the mathematical operations directly; here is my code and it works fine! public class Arithmetic { double mealCost; int tipPercent; int taxPercent; double tip; double tax; double totalCost; public static void main(String[] args) {

`Scanner scan = new Scanner(System.in); double mealCost = scan.nextDouble(); // original meal price int tipPercent = scan.nextInt(); // tip percentage int taxPercent = scan.nextInt(); // tax percentage scan.close(); double tip= (mealCost*(tipPercent))/100.0; double tax=(mealCost*(taxPercent/100.0)); double totalCost=(mealCost+tip+tax); int totalRoundedCost = (int) Math.round(totalCost); System.out.println("The total meal cost is " + totalRoundedCost+" dollars.");`

abhaychandrasin1 + 0 comments thks

rahul_dhakar38 + 0 comments [deleted]sharpe_wesley_ws + 0 comments i was curious if you knew why the parantheseis had to be around the second int in int totalRoundCost = (int) Math.round(totalCost); just want to understand it thanks i couldn't get the round until i looked here

narjesmhn + 0 comments Tnx..

tina_badulescu + 1 comment i dont know how to thank you !!!! i swear i didnt even think of creating new 'double' variables for "tip " and "tax" . i truggled a lot of finding a way to show my decimal part of an int; tried typecasting but instead of showing me 2.4 for the tip, it only displayed 2.00 .. thank you !

dombragagym + 0 comments did you get this error?: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864)

dombragagym + 0 comments How you dealinged with this error??? Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864)

`if you will try this input: 12.00 - you will get the error above!`

aniketv2000 + 0 comments use type casting

guptpriyanshu746 + 0 comments [deleted]

nudge_xyz + 4 comments I know this is old, but just for clarity...

"For eg: when you write (20/100) the quotient is 0" -- This is not correct, it returns 0 because you're using int and the Integer part of 0.20 is 0, if you used double it would work just fine. Mathematically, in this case, the order or the parentesis do not make a difference if you're using doubles: 12 * 20 /100 = 2.4 and 12 * (20/100) is also = 2.4.

gurramg90 + 0 comments that's correct. this cleared few of my speculations

rraijin + 0 comments helped a lot, thanks.

aaron_brandhagen + 0 comments thanks. this is just one of those things in programming that makes you scratch your head....programming if nothing else should be following mathematic protocol to the "T"

ssaulakh2 + 0 comments He said " Mathematically, in this case, the order or the parentesis do not make a difference if you're using doubles: 12 * 20 /100 = 2.4 and 12 * (20/100) is also = 2.4"

that's a straight lie.

Just try it out and you will find out how people lie to you so confidently when they are hiding behind the computer screens!

ssaulakh2 + 0 comments I tried this didn't worked for me!

hardikkamboj1 + 0 comments but the quotient in 240/100 is 2, therefore 240/100 should also return 2 instead of 2.40...

pavaniv + 0 comments Thank you.

Harishwaran + 0 comments Good Explanation. Thank you for sharing your knowledge.

jatin69 + 13 comments i used 100.0 but still failed the 4th test case. what am i missing ?

rohithreddy1201 + 1 comment [deleted]sonali_malhotra1 + 3 comments How do I do that?

meher_amey23 + 2 comments if(cost*(1+(tip/100.0)+(tax/100.0))-total>=total+1-cost*(1+(tip/100.0)+(tax/100.0))) { total=cost*(1+(tip/100.0)+(tax/100.0))+1; } else total=cost*(1+(tip/100.0)+(tax/100.0));

othinny + 1 comment Wow! If that's the best way in Java I'd suggest you try Python!

sagarkukreja + 3 comments you can use predefined function of java i.e, Math.round(). Pass decimal value as parameter, it will return nearest integer or long value for given decimal number.

Example :

After all calculations your are supposed to get 15.36. Now,

int totalCost=Math.round(15.36);

totalCost=15.

Anonymous_1998 + 0 comments [deleted]sairavi087 + 0 comments Great, thanks, i was trying to get a rounded value, but didn't want to use Wrapper classes or change the datatype given

dombragagym + 0 comments /* Complete the solve function below. */ static void solve(double meal_cost, int tip_percent, int tax_percent) { double tip = meal_cost*tip_percent/100; double tax = meal_cost*tax_percent/100; int totalCost = (int)Math.round(meal_cost + tip + tax); System.out.println(totalCost);

`/*Like that described above works better I think!! = */ Now I'm struggle with the error: Exception in thread "main" java.util.InputMismatchException any help?`

rohitnitd + 2 comments I think , it can be done in this way also

`int iTotalCost = (int)(dTotalCost); if(iTotalCost+1 < dTotalCost+0.5) iTotalCost++;`

sasa_pul + 8 comments As I understood it, casting a double into an int just cuts off the decimal part. So, the universal solution would be to just add 0.5 to a number and then cast it to int.

`double cost = 3.6; int roundCost; roundCost = cost + 0.5; printf("%d", roundCost);`

baczy + 0 comments Simple, but brilliant!

acidr00t + 0 comments This really is pretty clever.

kaurjit60 + 0 comments thankss

thelight_mn + 0 comments so good.

sidd_sajwan + 0 comments if 3.4 then minus will be good

mirna_alkhoreby + 0 comments I think your answer is very simple and there for it's brilliant

is there casting for a double method?

cause I'm facing that problem!

ken32293355 + 0 comments Very simple but smart!

vivekgangwar02 + 0 comments lol i did this in first time but i was in doubt if i'm using some shortcut.but now i am happy.

snehdeep_960 + 0 comments [deleted]

F_abi_an + 2 comments Just add 0.5 and then parse to int. Problem solved. Much more elegant :)

owenized + 3 comments Absolutely true. so my condition for this problem is:

if (totalcost-int(totalcost) > 0.50) { totalcost+=0.50; }

sakata_gintama + 1 comment its not working

owenized + 4 comments I got Aceepted Probably you printing the answer wrong. When you want to print the answer, use

cout << "The total meal cost is " << int(total) << " dollars.";

vijayashreeshet1 + 0 comments [deleted]Dilip_Rathore + 0 comments Thank you..

simrang861 + 0 comments my answer is correct . I have also typecasted it . but it is showing your answer didnt pass the test cases .

[deleted] + 0 comments yep. You are right.

impanan_is16 + 0 comments its nt working

venkatragupathy + 0 comments its working,tq

iarchitjain + 0 comments that way 0.5 will get rounded off to next integer too. I think that is wrong. maybe go for 0.49

mburnwal96 + 4 comments i think you have to try

float mealCost; int tipPercent; int taxPercent; float tip; float tax; float totalCost; scanf("%f",&mealCost); scanf("%d",&tipPercent); scanf("%d",&taxPercent); tip=(mealCost*(tipPercent/100.0)); tax=(mealCost*(taxPercent/100.0)); totalCost=(mealCost+tip+tax); printf("The total meal cost is %.0f dollars.",totalCost);

a_shivani63 + 2 comments could you please explain me why i couldnt pass the last test case .After trying your code it seemed to work fine.

ai4mrp + 1 comment can you paste your code?

a_shivani63 + 1 comment `double meal; float tax,tip; int total; /* Enter your code here. Read input from STDIN. Print output to STDOUT */ scanf("%lf",&meal); scanf("%e",&tip); scanf("%e",&tax); tip=meal*tip/100; tax=meal*tax/100; total=meal+tip+tax; printf("The total meal cost is %d dollars.",total); return 0;`

in this code i do realize the error that i should round the number to nearest integer but im keen to know how float rounds up the number to next nearest integer. moreover is it the only way to round the integer result?

ai4mrp + 3 comments double mealCost=14.31;

int intmealCost;

intmealCost=(int)mealCost;//intmealCost will be 14.

if((mealCost-intmealCost)>0.5)

`printf("%d",intmealCost+1);`

else

`printf("%d",intmealCost);`

i correct your code into:

`double meal; float tax,tip; double total; //change int to double scanf("%lf",&meal); scanf("%e",&tip); scanf("%e",&tax); tip=meal*(tip/100); tax=meal*(tax/100); total=meal+tip+tax; //if total=14.31 and you didnt change ,it will be 14. int inttotal=(int)total; if(total-inttotal>0.5)printf("The total meal cost is %d dollars.",inttotal+1); else printf("The total meal cost is %d dollars.",inttotal); return 0;`

my english isnt good.hope it can help you.

a_shivani63 + 0 comments thanks a lot for helping me out,i am really grateful to you. by the way your english is really good.

vishnupriya22611 + 1 comment int inttotal=(int)total; could u explain that what is the meaning of this

a_shivani63 + 0 comments suppose your total value is a float datatype the it retains only the integer value thereby elemnating the decimal value. this in turn is used to check if the decimal part is less than or greater than 0.5. if its greater than 0.5 it adds a number to inttotaland thereby you round the value to nearest integer. hope my answer helped you.

rishitam2701 + 1 comment the third testcase is failing

san6082 + 0 comments take total cost is of float type and in the time of printing them round them into .0 point(%.0f).

parvejgub191 + 0 comments Same problem Iam also faced.

Dhana_123 + 1 comment why should not we declare total cost as int type...when i declared it as int testcase4 is not success?????

watto33gm + 1 comment you should declare total cost as float and then print it like this

printf("the total cost is %.0f dollars",round(total_cost));

the round function will round the value of total cost to nearest integer and then diplay it without decimals.

You should use %.0f otherwise the cost will be rounded to nearesr integer but will be printed like 15.0000 so to avoid decimal use %.0f

julioarmaz + 0 comments Thats weird, my code passed passed all test cases except for the last one, and the printf("the total cost is %.0f dollars",round(total_cost)); allowed to pass the last test case. Not sure why though. Can someone explain why the code I wrote didnt pass the last case, because im not seeing why that is. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The code i wrote for the total cost is the following, this didnt pass the last case: totalCost is of type float.

cout<<"The total meal cost is "<< round(totalCost) <<" dollars."<

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The code i wrote entirely is the following:

void solve(double meal_cost, int tip_percent, int tax_percent) { float totalCost; double tip,tax;

`//Calculating Tip % tip = meal_cost * (tip_percent/100.0); //Calculating Tax % tax = meal_cost * (tax_percent/100.0); //Calculating Total Cost $ totalCost = meal_cost + tip + tax; printf("The total meal cost is %.0f dollars.",round(totalCost)); //cout<<"The total meal cost is "<< round(totalCost) <<" dollars."<<endl; //This line of code didnt pass 'Testcase 3'`

} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

ssaulakh2 + 0 comments I tried this with my own logic but it doesn't work!

Jayasree_Pilli + 0 comments thank you

quibbler + 4 comments its because in the last case the input is as follows: 10.25 17 5 the result will be:12.505 if you are simply typecasting then your answer will be 12,which is wrong because you have to "roundoff" not "truncate". so,here the output will be 13. ps-you will get the input/output used in test cases by clicking on the corresponding test cases.

meaux + 0 comments link ded

fraiyr + 2 comments Maybe you can explain to me why my answer of 13 is incorrect then? I'm casting to an int, and the other 3 test cases work fine, but for some reason test case 4 fails. When I checked my 'incorrect' answer, it shows me that my answer is 13...

meaux + 0 comments it has to do with rounding up/down numbers. the code isn't wrong. but there's a difference between the compilers. I just "cheated" and got done with it after looking for a way to get it right. There is a way, but that's above the level they're trying to teach.

ssaulakh2 + 0 comments I know what he did! I ran the whole code in a try catch block!

jchris1901 + 0 comments Isn't the result of the computation by itself 12 cuz 10.25 + 6.25 + 5.125 = 12.125

ssaulakh2 + 1 comment Thank you quibbler

`You Are a Life Saver!`

#include <bits/stdc++.h> using namespace std; int main() { double meal_cost; cin >> meal_cost; int tip_percent; cin >> tip_percent; float tip = (meal_cost * tip_percent)/100; int tax_percent; cin >> tax_percent; float tax = (meal_cost * tax_percent)/100; tax_percent = meal_cost+tax+tip+0.1; if(meal_cost == 10.25) cout<<"The total meal cost is 13 dollars."; else cout<<"The total meal cost is "<<tax_percent<<" dollars."; return 0; }

subodhsinghrath1 + 0 comments 3rd test case not passed. what,s the matter with this

rishabhishan + 1 comment If you`re using python, then instead of using int(totalMealCost) use int(

**round**(totalMealCost))This is because

int(10.99999) = 10 while round(10.99999) = 11.0

To convert 11.0 to 11 use int(11.0) = 11

reynolma + 0 comments thanks @rishabhishan

kiran0010 + 0 comments int t=tax+tip+meal cost+0.5,t=total amount just add 0.5 it's fix ur error the logic is if ur ans is 12.4 it's means it is below the 12.5 so the ans is 12 if ans is 12.6 the the ans is 12 also because the in is just cut the folt num so we add 0.5 the the value is cross 13 nd the ans is shown 13 .

Ray1984 + 1 comment There's also a round() in C++:

http://www.cplusplus.com/reference/cmath/round/

Afterwards you'll still need to cast to an int.

ediellopez2 + 0 comments I never knew there existed a round funtion in C++. Thank you, Ray1984!

h542672448 + 0 comments try this: if (total+0.5 > total_int +1): total_int+=1 print("The total meal cost is %d dollars." %total_int) else : print("The total meal cost is %d dollars." %total_int)

Donaatas + 0 comments i just added + 0.5f c++ rounds up to smallet number. if you get 15.99 the int of that will be 15, even thou you should pay 16. su by adding 0.5f you will allways evaluate good. :)

rarora02 + 0 comments same here

wrenthd + 0 comments I had this issue but changing from flooring the answer to rounding it fixed it for me. Because floored the answer is "The total meal cost is 12 dollars." But rounded (and the correct answer) it's "The total meal cost is 13 dollars."

iarchitjain + 0 comments `In C++, I used another int "t" as follows: t=totalCost; if(totalCost-0.5>t) totalCost = t+1; cout<<"The total meal cost is "<<(int)totalCost<<" dollars.";`

venkatragupathy + 0 comments 4th test case fail,why ?

ssaulakh2 + 0 comments same here!

kapploneon + 1 comment static void solve(double meal_cost, int tip_percent, int tax_percent) {

`float tip = (float) ((meal_cost*tip_percent)/100.0); float tax = (float) ((meal_cost*tax_percent)/100.0); float cost = (float) (meal_cost + tip + tax); int totalCost = Math.round(cost); System.out.printf("The total meal cost is %d dollars.",totalCost);`

}

meghamanjunath21 + 0 comments hI can you explain why did u convert it to float?

nanimasterpiece + 0 comments Thank You

ogookafor + 0 comments Thanks alot Allison

nilabjasarkar123 + 0 comments i face this same problem so i multliply tippercent with mealCost then devide by 100 answer is right but test case not accepted what should i do?

nikhil_iluri + 0 comments Thank you!

satish_paluvai + 3 comments The below code is also giving as wrong answer but we are curious to know why it is wrong .. can any one help us in knowing that ...

public static void main(String[] args) { Scanner scan = new Scanner(System.in); double mealCost = scan.nextDouble(); // original meal price int tipPercent = scan.nextInt(); // tip percentage int taxPercent = scan.nextInt(); // tax percentage scan.close();

`// Write your calculation code here. double tip= (mealCost*(tipPercent))/100.0; // System.out.println("tip is"+tip); double tax= (mealCost*(taxPercent))/100.0;`

// System.out.println("tax is"+tax); mealCost=mealCost+tip+tax;

`// cast the result of the rounding operation to an int and save it as totalCost int totalCost = (int) Math.round(mealCost); System.out.println("totalcost"+totalCost); // Print your result }`

Karthikrajan + 0 comments Thank you!..

eshikagupta159 + 1 comment [deleted]jarlvs_ + 2 comments don't forget to add (.) after dollars

mshsingh772 + 0 comments [deleted]_Kalpesh_ + 0 comments This was the exact mistake I made.Thanks

Dominik_Kesim + 0 comments Firstly, assuming your calculation is correct you are supposed to print out the exact same statement shown in the sample output, means: "the meal cost is 15 dollars." (this must be it lol) Secondly, depending on the PL you use, I assume it's java due to the code you have posted, it's uneccassary to put paranthesis around your multiplication since java considers that multiplication operators have precedence over addition/subtraction.

Hope this helps.

hepzibalizzie + 0 comments Thank u

Srinath_V + 0 comments Thank You!

ahmadelsir + 0 comments but could I cast it first and then * mealCoast ?

shub06 + 0 comments thank you.

gejommathew + 0 comments Thank you

prashanthdkumar + 0 comments Clear Clarification of Basics :).

Thank You!

Susmitha_Rachel + 1 comment Its not PEMDAS.. it is BODMAS rule which tells us the order of performing arithematic operations when there are more than one operations, i.e Bracket,Of,Division,multiplication,addition,subtraction.This is decreasing order of priority for performing different arithmatic operations.

GeloSoil + 0 comments [deleted]

rajeshbmelige1 + 0 comments Thank You Allison.

prasoon15pn + 0 comments Thanks a lot

h42300010 + 1 comment my program runs and gives the correct output but it's said to be incorrect. i do not know what i am doing wrong,any suggestions?Thank you in advance

/* Enter your code here. Read input from STDIN. Print output to STDOUT */

double mealCost; int tipPercent, taxPercent; double tip, tax, totalCost;`cin>>mealCost>>tipPercent>>taxPercent; //calculate tip and tax amounts tip = mealCost * ((double)tipPercent/100); tax = mealCost * ((double)taxPercent/100); //calculate total meal price totalCost = mealCost + tip + tax; double cost = round(totalCost); //display total meal price cout<<"The total meal cost is "<<cost<<" dollars"<<endl; return 0;`

}

Sarthak_281097 + 2 comments just add "." after dollars....

brooom + 0 comments thank you sarthak

manu_p13 + 1 comment Thanks!

Susmitha_Rachel + 1 comment :) !

NiharPawade + 0 comments [deleted]

hemantc307 + 2 comments int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */

double mealCost; int tipPercent; int taxPercent; cin>>mealCost; cin>>tipPercent; cin>>taxPercent; float tip,tax; double totalCost;`tip=(mealCost*tipPercent)/100; tax=(mealCost*taxPercent)/100; totalCost=mealCost+tip+tax; totalCost=(int)totalCost; cout<<"The total meal cost is "<<totalCost<<" dollars."; return 0;`

} please tell me what is wrong in this code ?

dinhtien95tn + 1 comment you can fix

tip=(double)(mealCost*tipPercent)/100;

tax=(double)(mealCost*taxPercent)/100;

double totalCost=mealCost+tip+tax;

//totalCost=(int)totalCost;

double cost = round(totalCost);

cout<<"The total meal cost is "<

return 0;

passion4science + 0 comments from the problem statement. the totalCost variable is an integer variable. double check again.

mukeshjha0261 + 2 comments you might be getting error for 4th case...this is because u need to calculate the roundoff of each component(tax and tip) individually instead of calculating roundoff after adding them example: tip=2.59=3(after roundoff) tax=4.67=5(after roundoff) so total=8

now ur mistaki is total=tip+tax=2.59+4.67=7.26=7(after roundoff)

try out this: if( (tip + 0.5) >= (int(tip) + 1) ) cout << int(tip)+1; else cout << int(tip);

ayush_sabadi + 0 comments Thax a lot buddy.only 1 case was failed..ur code worked

batchuthrishna + 0 comments Thank you so much....It really helped me :)

pattrickqueiroga + 0 comments Thank you a lot. I did not notice that until I read your comment.

varshini_5813 + 0 comments thank you :)

joezzame + 0 comments thnks!

kuldeep_ksc91 + 0 comments true

salunkhegayatri + 0 comments but how to write a program?

adi081996 + 0 comments I got the same problem but this does not solve my problem.

abhisheknigam + 0 comments Thanks, I also encountered this!

bunny698 + 0 comments thank you

joseph_rodrigue1 + 2 comments Please can you help me on this, I cant seem to round my answer. I tried putting plus one the totalCost but I fail the last test case.

using System; using System.Collections.Generic; using System.IO; using System.Linq;

class Solution { public static void Main() { double mealCost; double tipPercent; double taxPercent;

`mealCost = Double.Parse(Console.ReadLine()); tipPercent = Double.Parse(Console.ReadLine()); taxPercent = Double.Parse(Console.ReadLine()); int tip = (int) mealCost * (int) tipPercent / 100; double tax = (int) mealCost * (int) taxPercent / 100; double totalCost = (int) mealCost + tax + tip; Console.WriteLine("The total meal cost is {0} dollars.",totalCost); } }`

Dominik_Kesim + 0 comments I am just curious.. why are you parsing the read input to double?

kumaralok36 + 0 comments try to use Math.Round while Writing the value.

please refer the below code

double tip=0,tax=0,totalCost; double mealCost = Convert.ToDouble(Console.ReadLine()); int tipPercent = Convert.ToInt32(Console.ReadLine()); int taxPercent = Convert.ToInt32(Console.ReadLine());

`tip = mealCost * tipPercent / 100; tax = mealCost * taxPercent / 100; totalCost = mealCost + tip + tax; Console.WriteLine("Total Cost of meal is :" + Math.Round(totalCost)); Console.ReadKey();`

pandeyji + 0 comments Thanks

[deleted] + 0 comments Thanks! :)

qhdgk825 + 0 comments Thank you so much.

Liswin + 0 comments I didn't get the '%' part here. How is the multiplication happening with 0?

vmane858 + 0 comments I have added it as 100.0 bt still I'm facing it can u help me plz

paragjnath + 0 comments thank u

Pongo1250 + 0 comments you can also declare 100 as a double this way: mealCost*(tipPercent/(double)100)

Tunliar + 0 comments Hoho!! Thanks for that!!

ynieto9 + 0 comments ¡Gracias!

harish_akuluru + 0 comments Thanks a lot for the explanation..

DanDrachenberg + 0 comments Thank you 2 times more than anyone else here :)

kashif_bilal_al1 + 0 comments Thank You

sy254191 + 0 comments *

*why my code is giving error plz tell it is matching with the required output main() { double mc; float tip,tax; int ttip,tp,totalcost; scanf("%lf%d%d",&mc,&ttip,&tp); tip = (mc*((ttip)/100.0)); tax = (mc*((tp)/100.0)); totalcost =mc+tip+tax; printf("The total meal cost is %d dollars",totalcost); /* Enter your code here. Read input from STDIN. Print output to STDOUT*/ return 0; **srikrishshankar1 + 0 comments Some countries like in India we follow BODMAS which gives a different output.

gladkovslava + 0 comments Thank you)

slytherin_20 + 0 comments Thank you so much I was so confused before.

luis_arc_picazzo + 0 comments Casting does not work!!

amaheshar + 0 comments Thanks bro,

amaheshar + 0 comments Thanks bro,

nazimhmd4 + 0 comments Thankyou AllisonP

_N_PC_ + 0 comments works in the us, where order of operations is --MDAS, not so much anywhere else, where order of operations is --DMAS.

a1ubkh4n + 0 comments thank you...

deep_daman26 + 0 comments I m still not getting the correct answer.its giving output as 12 dollars i.e. taking tip and tax as zero.Where is the problem please help?

shabbiryamani + 0 comments What happened to good old BODMAS????

punkorange + 0 comments Thank you very much, this explains a lot too me, I spent more time trying to get this one than I should have because of this, I didn't think about two ints in parenthesis producing an int in the equation.

t_stephens67 + 0 comments Thanks

Michael_Gb + 0 comments Thank you!

m_k_developer95 + 0 comments thank you

317126510093CSE + 0 comments thank u so much for your clear explaination

[DELETED] + 0 comments [deleted]akanshrohal + 0 comments Thank you so much !

aditya_o1 + 0 comments Cool

skmill + 0 comments Thanks. Very helpful.

ashwinphilip27 + 0 comments Thanks! This explains it perfectly!

indranildey_rj + 0 comments thanks for this

iDontCodeGood + 0 comments Ahh, changing it to 100.0 fixed it, thank you! I never would have thought of that.

ssavagunji03 + 0 comments Thanks .. You taught me something new today.

bhimeshp14 + 0 comments hey can u explain why

int f=240; float t=(float)f/100; then t will be t=2.0

if float t=(float)f/100.0; then f=2.4;

Anonymous_1998 + 0 comments [deleted]zigfridus + 0 comments I think casting will allow to use parentheses:

double tip = mealCost * ((double)tipPercent / 100);

shyamkalariya + 0 comments You can explicitly conver nTipPercent to double ...

Your code should be

dMealCost * ((double)nTipPercent/100);

shyamkalariya + 0 comments You can explicitly conver nTipPercent to double ...

Your code should be

dMealCost * ((double)nTipPercent/100);

shyamkalariya + 0 comments You can explicitly conver nTipPercent to double ...

Your code should be

dMealCost * ((double)nTipPercent/100);

codermandy + 0 comments [deleted]1chetantamboli + 3 comments By using some simple math, single line is enough to solve all the test cases

cout<<"The total meal cost is "<<round(meal*(1+0.01*(tip+tax)))<<" dollars.";

Stelikas + 0 comments [deleted]Stelikas + 1 comment Brilliant.

mondleprasad + 0 comments good one

madhuripatwal08 + 0 comments plz explain

tanusreeghosh857 + 0 comments [deleted]ashwinphilip27 + 0 comments I had the same question on my mind. Thanks!

Noxsser + 1 comment #!/bin/python3 import math import os import random import re import sys # Complete the solve function below. def solve(meal_cost, tip_percent, tax_percent): if __name__ == '__main__': meal_cost = float(input()) tip_percent = int(input()) tax_percent = int(input()) tip = (meal_cost * tip_percent) / 100 tax = (meal_cost * tax_percent) / 100 totalCost = int(round(meal_cost + tip + tax)) print(totalCost) solve(meal_cost, tip_percent, tax_percent)

I'm having some problem with this. It just keeps showing me wrong answer.

Mind I add that when I switch the default code from C++ to Python 3 it shown me that the

`f __name__ == '__main__':`

doesn't have an indent. After I add it, I still get wrong answer.Please Help

vipindhariwal97 + 1 comment meal_cost = float(input())

`tip_percent = int(input()) tax_percent = int(input()) tip = (meal_cost * tip_percent) / 100 tax = (meal_cost * tax_percent) / 100 totalCost = int(round(meal_cost + tip + tax)) print(totalCost)`

^paste the above code in the function defintion of function 'solve' above,..,, not inside main

manojbolloju03 + 0 comments def solve(meal_cost, tip_percent, tax_percent): tip = (meal_cost * tip_percent) / 100 tax = (meal_cost * tax_percent) / 100 total_cost = int(round(meal_cost + tip + tax)) print(total_cost)

if**name**== '**main**': meal_cost = float(input())`tip_percent = int(input()) tax_percent = int(input()) solve(meal_cost, tip_percent, tax_percent)`

could you please help me

Stark749 + 2 comments - Your code did not pass this test case.
- Input (stdin)
- 12.00
- 20
- 8
- Your Output (stdout)
- The total meal cost is 15 dollars
- Expected Output
- The total meal cost is 15 dollars.
- Compiler Message
- Wrong Answer

got the answer still saying wrong!

vanshika_bhardw1 + 6 comments I guess the period after 15 dollars is the reason.

Stark749 + 0 comments thank you Vanshika_bhardw1, it worked.

monisha_1402120 + 1 comment I also has the same problem what to do???

vanshika_bhardw1 + 1 comment can you show the code here? i'll try figuring it out. @monisha_1402120

kandeepanece7 + 1 comment Can you please tell me the reason for this!

Your code did not pass this test case. Input (stdin) 12.00 20 8 Your Output (stdout) The total meal cost is 15dollars. Expected Output The total meal cost is 15 dollars. Compiler Message Wrong Answer

My code as below :-

import java.util.

*; import java.math.*;public class Arithmetic {

`public static void main(String[] args) { Scanner scan = new Scanner(System.in); double mealCost = scan.nextDouble(); // original meal price int tipPercent = scan.nextInt(); // tip percentage int taxPercent = scan.nextInt(); // tax percentage scan.close(); // Write your calculation code here. double tip = mealCost * tipPercent / 100 ; // System.out.println("tip is" +tip); double tax = mealCost * taxPercent / 100 ; // Sytem.out.println("tax is" +tax); double meal = mealCost + tip + tax; // cast the result of the rounding operation to an int and save it as totalCost int totalCost = (int) Math.round(meal); System.out.println( "The total meal cost is " +totalCost +"dollars."); // Print your result }`

}

meeds122 + 0 comments There needs to be a space after your inserted integer

rudra_pratap777 + 0 comments [deleted]harshitasharma23 + 0 comments OMG!! Thanks a lot Vanshika. Had the same problem, was banging my head as I had uploaded my code so many times. The period was the problem. Just happened to read this post.

shivanandgoudar + 0 comments hey what do you mean by period after 15 dollars .I am also facing the same problem can you suggest me

holly_johnsen + 0 comments Thanks! I had this same issue and I could not find that period somehow until reading this comment. Then of course once I saw it I couldn't fathom why I didn't notice it before!

abhitej655 + 0 comments just put dot(.) after 15 dollars in your print statement

adi7718002065 + 0 comments look at my code its not correct for 3rd test case of day 2

# !/bin/python3

import sys

if

**name**== '**main**': meal_cost = float(input()) tip_percent = int(input()) tax_percent = int(input()) tip_amount = meal_cost * tip_percent / 100 tax_amount = meal_cost * tax_percent / 100 total = meal_cost + tip_amount + tax_amount print( int(total))

mohakamo + 8 comments And this is the Solution in c++

`double mealCost; int tipPercent; int taxPercent; int totalCost; cin >> mealCost; cin >> tipPercent; cin >> taxPercent; tipPercent = round(mealCost * tipPercent/100); taxPercent = round(mealCost * taxPercent/100); totalCost = mealCost + tipPercent + taxPercent; cout << "The total meal cost is " << totalCost << " dollars.";`

essamgouda97 + 1 comment Thank you so much sir !!!

avi_dssd + 1 comment dont you think round() should be used on the final value we get, as shown in expalantion part of the problem also??? i have tried this and it is also passing all the test cases.So, your code will be soemthing like this: double mealCost, tip, tax; int tipPercent; int taxPercent; int totalCost;

cin >> mealCost; cin >> tipPercent; cin >> taxPercent;

tip = (mealCost * tipPercent/100); tax = (mealCost * taxPercent/100); totalCost = round(mealCost + tip + tax); cout << "The total meal cost is " << totalCost << " dollars.";

ankittiwari06 + 0 comments thank you sir

ankittiwari06 + 1 comment SIR what is wrong in this code

int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */

int tipPercent,taxPercent; float mealCost,tip,tax,totalCost; tip=(mealCost*tipPercent)/100.0; tax=(mealCost*taxPercent)/100.0; totalCost=mealCost+tip+tax; cin>>mealCost; cin>>tipPercent; cin>>taxPercent; int TotalCost = (int)round(totalCost); cout<<"The total meal cost is "<kuldeep_ksc91 + 0 comments System.out.printIn where is the error in it always said there is a compile error ..symbol cannont found

wheresbicki + 0 comments Is there any benefit to using cin vs scanf()?

selesta + 0 comments hiee thank u!! ur code is very simple nd effective

mbratanata + 1 comment I am not understanding why do we have to include: cin >> mealCost; cin >> tipPercent; cin >> taxPercent;

Can someone explain???

vgadidec96 + 0 comments It's like you are getting the input from the system itself. Check that you'll have 2 test cases to clear this testcase0 and testcase1. So which you give cin or scanf such that it defaultly checks both the testcase.

pat_laugh + 0 comments This code is wrong! If you have a cost of 15, and a tip and tax of 10% each, it would output 19 instead of 18 since it rounds prematurely! You need to round only the final result!

If it passed all test cases, then there need to be more test cases.

elassaad_y + 0 comments Your code is by the far the most simple ans traightforward one :) Thank you sir

arvinds6025 + 1 comment this is wrong.. you won't pass test case 1,2,3.

elassaad_y + 0 comments Thanks

charleshkang + 5 comments I'm doing this in swift but using the round() function for some reason does not work in Hackerrank. It works fine in playgrounds so I'm pretty confused

keithgrout + 0 comments If you didn't import Foundation, then that's probably the issue. I had the same problem.

backslash_f + 1 comment This works. (You can also use lround (returns a Int, which is the exercise's requirement for the output)):

`import Foundation let mealCost: Double = Double(readLine()!)! let tipPercent: Int = Int(readLine()!)! let taxPercent: Int = Int(readLine()!)! func tip() -> Double { return mealCost * (Double(tipPercent) / 100) } func tax() -> Double { return mealCost * (Double(taxPercent) / 100) } func totalCost() -> Int { return lround(mealCost + tip() + tax()) } print("The total meal cost is \(totalCost()) dollars.")`

tripathysmrutir1 + 0 comments Compile time error Compile Message File "solution.py", line 3 let mealCost: Double = Double(readLine()!)! ^ SyntaxError: invalid syntax-----This kind of error is showing..

diegommlima + 2 comments You need implement your "round function" like

`func round2(value: Float) -> Int { if Int(value+0.5) > Int(value) { return Int(value+1) } return Int(value) }`

This works fine!

Lashwind + 0 comments thx man, it problem fully eat my brain) Ps:tested over 100 combinations, on cpp and no catch any working it possible, really?

Thiaros + 1 comment This logic will not work for test case 3. Or any cases that returns total cost to be x.51 to x.55.

Lashwind + 1 comment Don't stuck on it, use pyton or java, in pyton they work on native function, i tested from x-0.9 to x+0.9 all func in cpp, trunc, ceil, round, etc... it's bad way - just use pyton! print(int(x)) it's all

raghav_gupta5294 + 0 comments for c++ u can use round function and use <#include cmath>

jbush1 + 0 comments [deleted]jbush1 + 0 comments var mealCost: Double = Double(readLine()!)!

var tipPercent: Int = Int(readLine()!)!

var taxPercent: Int = Int(readLine()!)!

var tip: Double {

`get { return mealCost * (Double(tipPercent) / 100) }`

}

var tax: Double {

`get { return mealCost * (Double(taxPercent) / 100) }`

}

var totalCost: Double {

`get { return mealCost + tip + tax }`

}

print("The total meal cost is (lround(totalCost)) dollars.")

brandon_dicicco + 1 comment You would want to do this in a more effient way but broke down how each one was caculated in C#.

// Get the Tax double tax = (meal_cost * tax_percent) / 100; // Get the Tip double tip = (meal_cost * tip_percent/100); // Total Cost double totalCost = meal_cost + tax + tip; // Round the total cost and output to console Console.WriteLine("The total meal cost is " + Math.Round(totalCost) + " dollars.");

olcaytoselcuk + 0 comments i did that way:

int realTotalCost = (int)totalCost;

but program didnt accept this solution and i tried your solution and program accepted it. thanks.

Dil_Waku + 1 comment here is the thing. i passed all the test cases except 3rd, the calculation shows 20.75 - mealCost 10 - tipPercent 3 - taxPercent

in my calculation 12*10 = 120 12*3 = 36 (120+ 36)/100 = 1.56 1.56 + 20.75 = 22.31 so even you round up 22.31; the result is 22. but your test case expect it to be 23. how come? can you kindly explain this scenario ??

sweadon + 1 comment "in my calculation 12*10 = 120 12*3=36..." But the meal cost is 20.75 so it would be

20.75*10 = 207.5 and

20.75*3 = 62.25 so

(207.5+62.25)/100 = 2.6975 and finally

2.6975 + 20.75 = 23.4475 which rounds to 23.

keerthishanmu + 0 comments thank you sweadon its very helpful..

bhuvanshukla + 2 comments i am able to run my code on dev c++ with correct output but here it is not accepting my code for the last case 10.25 17 5 as it says that the output is 13(hackerrank compiler) whereas dev C++ output is giving it as 12.

bhuvanshukla + 1 comment please help

sweadon + 3 comments C rounds 0.5 down, so I guess C++ does, too. 10.25 with 17% tip and 5% tax would be 12.505 which would round to 13. If you're rounding the tax and the tip before adding them to the meal cost then you'd be getting 12.50 which would round to 12.

keithf + 2 comments Using the floor method will provide more consistent results:

mealCost = mealCost + tip + tax; //(assuming tip and tax were calculated correctly)

cout << floor(mealCost + 0.5) << endl;

If adding 0.5 brings it to an even number, floor returns the same number, otherwise it always rounds down, which is the result we are after.

rahulnaik + 1 comment tanks kethf ur code is so helpful. bu what if the case it comes exactly at the point 12.50

david_bruchmann + 1 comment That's not defined in the test. In PHP you can define if it shall be rounded up or down then but you've to get that detail then to know what to do or to try with both settings and check if the test-cases behave different. Rounding in PHP

calgahan + 1 comment Hi David could you give me a hand tryinf to solve this in PHP. I keep failing the thrid test case (Testcase 2). I think its the round function as it keeps round up but it should round down. The amount when calculated is £22.31. When its out put it rounding to £23. Do you know how to fix this.

david_bruchmann + 0 comments I think you should look up the round-function in detail. I used round() with 3 parameters where the last one determines how rounding is done. Here is the link: http://php.net/manual/en/function.round.php

learner_codes + 0 comments thanks friend.

splendid!!

abhigyan_Kumar + 0 comments its not c or c++ but maths

dharmendra_devr1 + 0 comments # include

int main(){ int taxp,tipp,total; double mc,tax,tip; scanf("%lf %d %d",&mc,&taxp,&tipp); tax=(taxp/100.0)*mc; tip=(tipp/100.0)*mc; //printf("%lf\n%lf\n",tax,tip); printf("The total meal cost is %d dollars.",(int)(mc+tax+tip));

`return (0);}`

Ank05 + 2 comments I am facing the same issue with the third test case while using the C language.

ksarankumar21 + 1 comment try this for round off::

int roundNo(float num)

{ return num < 0 ? num - 0.5 : num + 0.5; }

bhuvanshukla + 1 comment thanks you i was making a mistake in declaring the type of variable.

Ank05 + 0 comments :-)

khsyo + 1 comment

Sort 1993 Discussions, By:

Please Login in order to post a comment