Search code examples
c++rounding-error

Rounding errors in lethal dose calculator program


I was given an assignment that asks me to find the lethal dose of soda in grams for an inputted weight from the user. I am having many issues with rounding errors... this should be simple and not sure why I'm having so many issues with it. For example, here are a couple of inputs and outputs that are causing problems. Thanks in advance!

Input of 1 1000 275: expected [124850000, 356714286] but found [1.2485e+08, 3.56714e+08]

Input of 60 390 130: expected [383630, 1096086] but found [383630, 1.09609e+06]

/**
 *  @author 
 *  @date 2-2-22
 *  @file h02.cpp
 */
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;


/**
 * Finds lethal dose (in grams) of artificial sweetener for a given dieter weight.
 * Also finds the number of cans of soda that would be lethal for a given weight.
 * @return 0 for success.
 */
int run()
{
    // Add your implementation comments here

    // Write your code here
    
const double dose_per_can {.001}; // percentage of lethal sweetener in one can
const int soda_weight {350}; //in grams
const int pound_to_grams {454}; //in grams
double dieter_weight {};
double mouse_weight {};
double mouse_lethal {};
double dieter_lethal {}; // lethal dose in grams to human/dieter
double lethal_ratio {};
float lethal_per_can {}; //how many grams of art sweetener in a can
double dieter_lethal_cans {};


cout << "Enter mouse weight, lethal dose for mouse (grams), and desired wight of dieter (pounds): " << endl;
cin >> mouse_weight >> mouse_lethal >> dieter_weight;

lethal_ratio = mouse_lethal / mouse_weight; //finding the ratio between the dose given and the weight of the mouse
                                            //lets us use this weight ratio on humans

dieter_lethal = lethal_ratio * (dieter_weight * pound_to_grams); //grams of sweetener that is lethal to dieter with given weight

lethal_per_can = soda_weight * dose_per_can; //find how many grams of sweetener in 1 can.. ends up being constant of .35
dieter_lethal_cans = dieter_lethal / lethal_per_can; // finds how many cans would be lethal to dieter

cout << "Lethal dose in grams, cans is [" << dieter_lethal << ", " <<round(dieter_lethal_cans) << "]" << endl;

    return 0;
    

}

Solution

  • The round you use returns a floating point value. You need lround - see here: https://en.cppreference.com/w/cpp/numeric/math/round

    cout << "Lethal dose in grams, cans is [" << lround(dieter_lethal) << ", " 
        << lround(dieter_lethal_cans) << "]" << endl;
    

    Lethal dose in grams, cans is [124850000, 356714292]