有人可以解释一下这个 c++ 代码有什么问题吗?

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

本文关键字:c++ 代码 什么 问题 解释 一下      更新时间:2023-10-16

下面的程序是Walter J Savitch的Absolute C++的一个例子。我正试图运行这段代码,但遇到了错误,但我不知道为什么。这是一个用户定义函数的示例。函数round()应该在对double值进行四舍五入之后返回int

#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] :

https://i.stack.imgur.com/ABj8G.png这就是我犯的错误。

如果您的错误回合已经在另一个文件中定义,请使用新名称创建一个新回合,它应该可以使用

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));
}

一开始,我不知道你为什么要实现round()函数,因为有一个round(

其次,您错误地实现了round()函数。你需要这样的东西:

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