lawlorz
lawlorz

Reputation: 3

C++ Warning C4244 'return': conversion from 'double' to 'int', possible loss of data Visual Studio 2015

New to C++, following a tutorial and trying to expand on it. My program compiles but I am getting the error "warning C4244: 'return': conversion from 'double' to 'int', possible loss of data" on line 23: end: return(n1); when compiling which means my calculator results are incorrect, ignoring decimal places and treating everything as an integer. I cannot find any instance in my code of an int apart from the 1 which I have specifically used. No doubles should be converting at all. Can anyone please have a look and let me know where I've gone wrong? I've attempted turning my current int into a double, and also using various other formatting styles to no avail.

#include "stdafx.h"
#include <iostream>
#include <cstdint>

using namespace std;

int getNumber(int16_t x)
{
    double n1{};

    if (x == 1)
    {
        cout << "First number: ";
        cin >> n1;
        goto end;
    }
    else if (x == 2)
    {
        cout << "Second number: ";
        cin >> n1;
        goto end;
    }
        end: return(n1);
}

int getOperator()
{
    char op{};
    cout << "Operator (+, -, *, /): ";
    cin >> op;

    return(op);
}

void printAnswer(double n1, char op, double n2)
{
    if (op == '+')
        cout << n1 << " + " << n2 << " = " << (n1 + n2) << '\n';
    else if (op == '-')
        cout << n1 << " - " << n2 << " = " << (n1 - n2) << '\n';
    else if (op == '*')
        cout << n1 << " * " << n2 << " = " << (n1 * n2) << '\n';
    else if (op == '/')
        cout << n1 << " / " << n2 << " = " << (n1 / n2) << '\n';    
}

int main()
{
    cout << "Please enter two numbers and an operator to perform a calculation." << endl;

    double n1(getNumber(1));
    char op(getOperator());
    double n2(getNumber(2));

    printAnswer(n1, op, n2);

    return(0);
}

Upvotes: 0

Views: 6326

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The warning message is pretty clear. In the function you have defined to get your numbers the return type is int

    int getNumber(int16_t x)
 // ^^^

while you actually pass a double type to the return statement.

To get rid of the warning fix the function return type:

    double getNumber(int16_t x)
 // ^^^^^^

As a side note: Please don't use goto, especially not if it's completely superfluous. All of your code paths directly lead to label end: anyways.

Upvotes: 3

Related Questions