简体   繁体   中英

Can someone please explain what's wrong with this c++ code?

The program below is an example from Absolute C++ by Walter J Savitch. I'm trying to run this code but getting errors but I cant figure out why. This is an example of user defined functions. The function round() is supposed to return an int value after rounding a double value

#include <iostream>
#include <cmath>

using namespace std;

int round (double number);

int main()
{ 
    double doubleValue;
    char ans;

    do
    {
        cout << "Enter a double value: ";
        cin >> doubleValue;
        cout << "rounded that number is " << round(doubleValue) << endl;
        cout << "Again?" << endl;
        cin >> ans;
    }while(ans == 'y' || ans == 'Y');

    cout << "end of testing " << endl;
    return 0;
}

int round(double number)
{
   return static_cast<int>(floor(number + 0.5);
}

[1]:

http://i.stack.imgur.com/ABj8G.png this is the errors that I'm getting.

At first, I don't know why you have implemented round() function, since there is a round() function is c.

Second, you have implemented round() function incorrectly. you need something like this:

int round(double num)
{
return static_cast<int>(num+0.5);
}

From your error round is already defined in another file, make a new one with a new name and it should work

int my_round (double number);

int main()
{ 
    // ... 
    cout << "rounded that number is " << my_round(doubleValue) << endl;   
    // ... 
}

int my_round(double number)
{
    return static_cast<int>(floor(number + 0.5));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM