ron*_*san 1 c++ rounding visual-studio-2008 visual-c++
我有以下visual c ++代码
#include <iostream>
#include <string>
#include <sstream>
#include <math.h>
using namespace std;
int Main()
{
double investment = 0.0;
double newAmount = 0.0;
double interest = 0.0;
double totalSavings = 0.0;
int month = 1;
double interestRate = 0.065;
cout << "Month\tInvestment\tNew Amount\tInterest\tTotal Savings";
while (month < 10)
{
investment = investment + 50.0;
if ((month % 3 == 0))
{
interest = Math::Round((investment * Math::Round(interestRate/4, 2)), 2);
}
else
{
interest = 0;
}
newAmount = investment + interest;
totalSavings = newAmount;
cout << month << "\t" << investment << "\t\t" << newAmount << "\t\t" << interest << "\t\t" << totalSavings;
month++;
}
string mystr = 0;
getline (cin,mystr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它给我使用Math :: Round的问题,我真的不知道如何使用visual c ++来使用这个函数
Math :: Round()是.NET,而不是C++.
我不相信C++中有直接的平等.
你可以这样编写自己的(未经测试):
double round(double value, int digits)
{
return floor(value * pow(10, digits) + 0.5) / pow(10, digits);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,Math :: Round是.NET框架的一部分,并不是普通C++规范的一部分.有两种可能的解决方案.
第一种是自己实现圆函数,使用<cmath>中的ceil或floor并创建类似于以下的函数.
#include <cmath>
inline double round(double x) { return (floor(x + 0.5)); }Run Code Online (Sandbox Code Playgroud)
第二个是为您的C++程序启用公共语言运行时(CLR)支持,这将允许访问.NET框架,但代价是它不再是真正的C++程序.如果这只是一个供您自己使用的小程序,这可能不是什么大问题.
要启用CLR支持,请执行以下操作:
右键单击解决方案,然后单击属性.然后单击配置属性 - >常规 - >项目默认值.在Common Language Runtime支持下,选择Common Language Runtime Support选项(/ clr).然后单击Apply并单击OK.
接下来,将以下内容添加到代码顶部:
using namespace System;Run Code Online (Sandbox Code Playgroud)
现在,您应该可以像使用任何其他.NET语言一样使用Math :: Round.
| 归档时间: |
|
| 查看次数: |
19461 次 |
| 最近记录: |