+ 1

Shopping practise C++ answer keeps coming out negative

#include <iostream> using namespace std; int main() { // your account's balance auto balance = 2452.4; // price for each notebook auto price = 259.99; // Task: calculate the number of notebooks you can afford and output it. // Hint: use an integer to store the result. int notebooks = balance/price; cout << notebooks; cout<< endl; // Task: calculate the amount left over on your account after the purchase and output it on a new line. // Hint: calculate the total price of the purchase, then substract it from the balance. auto newbalance = notebooks * price; auto newBalance = newbalance - balance; cout << newBalance; } Answer spits out 9 -112.49 I separated the variables thinking that might have caused it with no luck

21st May 2025, 1:01 AM
Timothy Anderson
1 Réponse
+ 3
it's negative because you're subtracting in the wrong order. it's not newbalance when you compute notebooks * price, it's cost. you subtract cost from balance to find out how much is left. #include <iostream> using namespace std; int main() { auto balance = 2452.4; auto price = 259.99; int notebooks = balance/price; cout << notebooks << endl; auto cost = notebooks * price; cout << cost << endl; balance -= cost; cout << balance; }
21st May 2025, 1:51 AM
Bob_Li
Bob_Li - avatar