I have the following visual c++ code
#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;
}
But its giving me problems using Math::Round, truly I don't know how to use this function using visual c++
Math::Round() is .NET, not C++.
I don't believe there is a direct equal in C++.
You can write your own like this (untested):
double round(double value, int digits)
{
return floor(value * pow(10, digits) + 0.5) / pow(10, digits);
}
Unfortunately Math::Round is part of the .NET framework and is not part of the normal C++ spec. There are two possible solutions to this.
The first is to implement the round function yourself, using either ceil or floor from <cmath> and creating a function similar to the following.
#include <cmath>
inline double round(double x) { return (floor(x + 0.5)); }
The second is to enable Common Language Runtime (CLR) support for your C++ program, which will allow access to the .NET framework, but at the cost of having it no longer be a true C++ program. If this is just a small program for your own use, this probably isn't a big deal.
To enable CLR support, do the following:
Right click your solution and click properties. Then click Configuration Properties -> General -> Project Defaults. Under Common Language Runtime support, choose the option Common Language Runtime Support (/clr). Then click Apply and OK.
Next, add the following to the top of your code:
using namespace System;
Now you should be able to use Math::Round as with any other .NET language.
Just ran into this, and it is now 2013.
This is supported in C11, not older versions. So yes, the approved answer was appropriate in '09.
If you are using C11 and you do
include <math.h>
you should be able to call "round",
Such that:
double a = 1.5;
round(a);
Resulting in:
a == 1.0
AFAICT cmath (math.h) doesn't define a Round function, nor a Math namespace. see http://msdn.microsoft.com/en-us/library/7wsh95e5%28VS.80,loband%29.aspx
You might be better off adding 0.5 and using floor() as mentioned in another post here to get basic rounding.
精彩评论