![](/img/trans.png)
[英]can someone please explain what is wrong in this c++ code and provide a solution
[英]Can someone please explain what's wrong with this c++ code?
下面的程序是來自 Walter J Savitch 的 Absolute C++ 的一個示例。 我正在嘗試運行此代碼但出現錯誤,但我不知道為什么。 這是用戶定義函數的示例。 函數round()
應該在舍入double
int
值后返回一個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]:
http://i.stack.imgur.com/ABj8G.png這是我得到的錯誤。
一開始,我不知道你為什么要實現round()函數,因為有一個round()函數是c。
其次,您錯誤地實現了 round() 函數。 你需要這樣的東西:
int round(double num)
{
return static_cast<int>(num+0.5);
}
從你的錯誤回合已經在另一個文件中定義,用新名稱創建一個新的,它應該可以工作
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.