| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
C++ math operators
I'm learning C++ and need to know if there is a math operator for raising a number to a power. Example 2 sqaured would be written how???? (Other than 2 * 2)
|
|
#2
|
|||
|
|||
|
You can use the power operator: ^
eg. 2 to the power of three would be 2^3; |
|
#3
|
|||
|
|||
|
Thank you
|
|
#4
|
|||
|
|||
|
C++ does not have a ^ operator. Use the pow() function.
Example: 2 to the power of 3 would be pow(2,3) |
|
#5
|
|||
|
|||
|
Oops. Sorry My mistake - that's VB, not C++
![]() |
|
#6
|
|||
|
|||
|
Well now I have a new problem. I have been trying to figure it out for hours, and no luck.
I'm trying to have the program calculate this equation: N = P * 2 ^ (T/10). T is days, and integer. P is any whole number, an integer. N should be a decimal (double), but it always comes out to be another whole number. I'm using a loop to calculate N, when P is entered by the user, for 10 days. IE: for (T=1; T<=10; T++) { N = P * (2^(T/10)); cout << T; cout << " " ; cout << N << '\n'; } This is probably a very simple thing, but I can't figure out why the output is wrong. Any ideas? |
|
#7
|
|||
|
|||
|
Ok, I did this once. if you are calculating with integers the result will be integer. try for instance printing the value of you T/10.... you wold be surprised. Even if you know these T and P should be integers, declare them as floats, and see what happens.
Now I have a little prolem: does anybody know what is the function in c++ which gives the maximum between two values? cheers, Kazu. Quote:
|
|
#8
|
|||
|
|||
|
Kazu is essentially right, but I wouldn't declare an integer as a float if it should be an integer. Declare T and P as integers, but convert them for the calculation:
for (T=1; T<=10; T++) { N = static_cast<double>P * (2^(static_cast<double>T/10.0)); cout << T; cout << " " ; cout << N << '\n'; } This way you retain the benefits of knowing that T and P are integers, as they are supposed to be for the rest of the program (also notice the division is by 10.0). Hope this was in time to help... |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > C++ math operators |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|