What's the difference between llround() and round() function in C++? - c++

so the reason why I have this question is that I was doing a problem in which we had to round the final answer. Now,
cout << round(answer); //this didn't pass one test case
//the following block of code passed all test cases
if (answer-(int)answer>0.5) cout << int(answer)+1;
else cout << (int)answer;
cout << llround(answer); //this passed all test cases
So, what is the difference between round() and llround() for this type of behavior? If the answer variable would have been so big to not fit in the int type, then if-else block of code shouldn't have worked either. So what am I missing?
Thank you!

round() returns a floating point value, while your alternatives return integer value. With the default formatting of cout, there should be no difference in the output, but if you have changed the formatting, there might be a difference:
double answer = 1.5;
cout << round(answer) << " " << llround(answer) << "\n"; // Prints 2 2
cout << std::fixed << setprecision(5);
cout << round(answer) << " " << llround(answer) << "\n"; // Prints 2.00000 2

Related

Unexpected result for "&array" [duplicate]

This question already has answers here:
Why are `&array` and `array` pointing to the same address?
(2 answers)
How come an array's address is equal to its value in C?
(6 answers)
Closed 1 year ago.
I am confused about array usage as pointer and result of that. Let me explain. When I try this
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int *myPointer = &a;
cout << "*myPointer: \t" << *myPointer << endl;
cout << "myPointer: \t" << myPointer << endl;
cout << "&myPointer: \t" << &myPointer << endl;
cout << "myPointer[0]: \t" << myPointer[0] << endl;
cout << endl;
int myArray[3] = {1,2,3};
cout << "*myArray: \t" << *myArray << endl;
cout << "myArray: \t" << myArray << endl;
cout << "&myArray: \t" << &myArray << endl;
return 0;
}
All of output are exactly what I expected, except last one (&myArray). Lets say my ram something like this:
Address
Variable
Value
0xA100
a
10
0xA101
myPtr
0xA100
0xA102
1
0xA103
2
0xA104
3
0xA105
myArray
0xA102
If I imagine it correctly, then how "&myArray" can be same with "myArray"? Actually, I think it can be anything but 0xA102. Because, this result means that "myArray" is in 0xA102 and value of pointed by myArray is in 0xA102 too. And I know it is weird but it means also, as a value "1", is in 0xA102 too. (At least I got it from this result).
So, I cannot catch the point. I think the result has to be 0xA105 if "&" means address. If yes, why result is not 0xA105. If not, why they have different usage although arrays are pointers.
Is there anybody can clarify the matter?
Thanks.

How to print complex numbers in C++

I am playing around with classes in C++. Currently I am working on a class for complex numbers and want to be able to print them in the following format: -2+3i, 1-4i. That means, that I want the real part to have only a sign if it is negative. In contrast the imaginary part should have always a sign whether it is positive or negative.
I tried the following which did not work as expected:
inline void Complex::print() const {
std::cout << x;
std::cout << std::showpos << y << "i" << std::endl;
}
This method prints also for the real part the sign if it is positive. Why does std::showpos affect the first line?
Is there any better way to do that?
showpos is "sticky", and applies to every following number until it's changed back with noshowpos.
You can use showpos with a local stream to avoid messing with std::cout:
inline void Complex::print() const {
std::ostringstream y_stream;
y_stream << showpos << y;
std::cout << x
<< y_stream.str() << 'i'
<< std::endl;
}
When the showpos format flag is set, a plus sign (+) precedes every non-negative numerical value inserted into the stream (including zeros). This flag can be unset with the noshowpos manipulator.
Minor change in your code:
inline void Complex::print() const {
std::cout << std::noshowpos << x;
std::cout << std::showpos << y << "i" << std::endl;
}
That's because the std::showpos flag affects every number inserted into the stream. (http://www.cplusplus.com/reference/ios/showpos/)
Have you tried using if statements?
if (x > 0)
{
std::cout << "+";
}
If you never use std::noshowpos, std::cout will keep the showpos flag, so that next time you call print() it affects x (and any other number you ever print with std::cout in your program).
So either use std::noshowpos directly after printing y:
std::cout << std::showpos << y << std::noshowpos << "i" << std::endl;
or directly before printing x:
std::cout << std::noshowpos << x;

How to output an interger which is calculated to two decimal places?

It is easy to output a double value which is calculated to two decimal places.
And the code snippet is below:
cout.setf(ios_base::showpoint);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.precision(2);
cout << 10000000.2 << endl; // output: 10000000.20
cout << 2.561452 << endl; // output: 2.56
cout << 24 << endl; // output: 24 but I want 24.00, how to change my code?
How to output an interger which is calculated to two decimal places? I want 24.00 as an output.
It depends on what your 24 is.
If it is a hard-coded value, you can just write:
std::cout << 24.00 << std::endl;
If it's an integer variable, write this:
std::cout << static_cast<double>(myIntegerVariable) << std::endl;
Don't use any of the suggested approaches like adding ".00" as this will break your code if you want to change the precision later.
A rewrite of completeness, please try with following
#include <iostream>
#include <iomanip>
int main()
{
int i = 24;
std::cout << std::fixed << std::setprecision(2) << double(i) << std::endl;
// Output: 24.00
}

C++/CPP Reading an added hex address

I'm still relatively new-ish to CPP but I can't find any source that has my issue. My IDE is MSVC 2017 Preview and my desired outcome is to add two hex addresses together, then read the address' value. I'm not sure why but it's not playing nicely with adding hex numbers. I'll give you my current example:
int number;
ReadProcessMemory(pHandle, (void*)(0x37c90000 + 0xE29FE8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x37c90000 + 0xE29FE8) << std::endl;
ReadProcessMemory(pHandle, (void*)(0x38ab9fe8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x38ab9fe8) << std::endl;
std::cout << "a = " << (0x37c90000 + 0xE29FE8) << std::endl;
std::cout << "b = " << (0x38ab9fe8) << std::endl;
My predicted outcome of this code would be that both ReadProcessMemory should get the same exact same value, but instead only the second ReadProcessMemory (with the already added hex value) returns properly.
Furthermore, cout-ing A and B report the exact same address. If that's the case, why is ReadProcessMemory throwing a tantrum and reporting a negative number on the first ReadProcessMemory?
Here's my outcome with the code above:
-331287296 for 38ab9fe8
ec40f500 for 38ab9fe8
a = 38ab9fe8
b = 38ab9fe8
Apologies but I truly can't figure out why they're different in any way.
No that seems about right. 0xec40f500 is the unsigned hexadecimal representation of the decimal signed value -331287296. Please learn about two's complement representation of negative numbers.
The problem is, I believe, the std::hex manipulator, which is sticky. If you in the second case use std::dec both numbers will be displayed as decimal:
// Second output
std::cout << std::dec << number << " for " << std::hex << (0x38ab9fe8) << std::endl;
// ^^^^^^^^
// Display *all* following numbers as decimal
Or use std::hex in the first output:
// First output
std::cout << std::hex << number << " for " << (0x37c90000 + 0xE29FE8) << std::endl;
// ^^^^^^^^
// Display *all* following numbers as hexadecimal
Of course, if you intend for number to be unsigned, you need to explicitly say so when defining the variable. Perhaps it would be easier for you to see the connection between 0xec40f500 and the unsigned decimal value 3963680000?

What to do when an equation returns nan as an answer?

I've been having a slight issue with my program, what I'm trying to do is develop a way for users to simulate the possible strengths of passwords. This is assuming that all passwords are permutations (weird I know, but I presume that this is to stop data from becoming even more unwieldy.) using the equation...
//n!/(n-r)! when n! = (e^-n)*(n^n) sqrt(2(pi)n). When n is number of characters in use and r is length of password
No matter what I put I receive nan as an answer. I thought that perhaps my equation was off (maybe somehow I was dividing by zero) so I reworked it and simplified it a great deal. But that didn't seem to be the problem, though I feel that this got me closer to being correct. But I had the thought that maybe numeric overflow is having an effect here? But I really don't know how to fix something like that. I tried jumping from different data types but nothing seemed to work.
I have a problem with the modulus too. It returns back numbers less than zero for time, so with my noobish knowledge that tells me that maybe I'm overflowing it again but how else am I going to use % without defining it as an int? Maybe fixing the above problem will work out this one?
I would be beyond grateful for any help given to me. How does one go about dealing with return values of nan? Is there a step by step status quo for solving it? Is it pretty much always overflow or could it be something else?
The code itself.
#include <iostream>
#include <cmath>
using namespace std;
const int SECONDS_IN_YEAR = 31556926;
const int SECONDS_IN_DAY = 86400;
const int SECONDS_IN_HOUR = 3600;
const int SECONDS_IN_MIN = 60;
int main()
{
int passwordLength ,characterSymbols;
double instructionsPerSecond, instructionSuccess;
////////////////////////////////////////////////////////////////////////////////
//Equations needed
// n!/(n-r)!
//n is the number of letters in the alphabet
//and r is the number of letters in the password
// n! = (e^-n)*(n^n) sqrt(2(pi)n)
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
// (n-r)
double characterMinusLength= (characterSymbols-passwordLength);
// (n-r)! = (e^-(n-r)) * ((n-r)^(n-r)) * sqrt(2(pi)(n-r))
double denominatorFactorial = ((pow(M_E, -(characterMinusLength)))*
(pow((characterMinusLength),(characterMinusLength)))
* (sqrt(2*M_PI*(characterMinusLength))));
// n!/(n-r)!
long double passwordPermutation = (numeratorFactorial / denominatorFactorial);
// (passwords)* (instructions/Password) * (seconds/instruction) = sec
int passwordSeconds = (passwordPermutation * instructionSuccess)
*(1/instructionsPerSecond);
int passwordMin = passwordSeconds / SECONDS_IN_MIN ;
int passwordHour = passwordSeconds / SECONDS_IN_HOUR;
int passwordDay = passwordSeconds / SECONDS_IN_DAY ;
int passwordYear = passwordSeconds / SECONDS_IN_YEAR;
////////////////////////////////////////////////////////////////////////////////
//Explain purpose of program
cout << "This program is designed to simulate the strength of passwords." << endl;
//Ask for alphabet
cout << "But first, share with me the max number of characters you'd be using."
<< endl;
cin >> characterSymbols;
//Reflect information
cout << "We will be using " << characterSymbols << " character symbols to "
<< " construct the password.\n" << endl;
///////////////////////////////////////////////////////////////////////////////
//Input length of password
cout << "\n\nWill you give me the length of proposed password?" << endl;
cin >> passwordLength;
//Repeat information
cout << "The password length will be " << passwordLength << "." <<endl;
//cout permutations
cout << "This would lead to " << passwordPermutation << " unique password\n"
<< endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for computer strength
cout << "How powerful is this computer? How many instructions per second " << endl;
cout << "can it accomplish?" << endl;
cin >> instructionsPerSecond;
//Read out computer strength
cout << "The computer can do " << instructionsPerSecond << " instructions/second"
<< endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for instructions/password
cout << "The number of instructions needed to test your password is." << endl
<< endl;
cin >> instructionSuccess;
//reflect
cout << "This computer can do " << instructionSuccess
<< " instructions/password" << endl;
////////////////////////////////////////////////////////////////////////////////
cout << "\n\nThe amount of seconds it'll take to crack this passcode is... "
<< endl << passwordSeconds << " seconds.\n\n\n\n\n" << endl;
////////////////////////////////////////////////////////////////////////////////
//Reflect all information in an easily readable table
cout << "Number of character symbols using... " << characterSymbols << endl;
cout << "Length of password... " << passwordLength << endl;
cout << "Number of permutations... " << passwordPermutation << endl;
cout << "Instructions per second... " << instructionsPerSecond << endl;
cout << "Instructions per password..." << instructionSuccess << endl;
cout << endl << endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Add in conversions for min, hour, day, years
cout << "Number of seconds to break..." << passwordSeconds << endl;
cout << "Converted to minutes..." << passwordMin << endl;
passwordMin = passwordSeconds / SECONDS_IN_MIN;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to hours..." << passwordHour << endl;
passwordHour = passwordSeconds / SECONDS_IN_HOUR;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to days..." << passwordDay << endl;
passwordDay = passwordSeconds / SECONDS_IN_DAY;
passwordSeconds = passwordSeconds % SECONDS_IN_DAY;
cout << "Converted to years..." << passwordYear << endl;
passwordYear = passwordSeconds / SECONDS_IN_YEAR;
passwordSeconds = passwordSeconds % SECONDS_IN_YEAR;
return (0);
}
"nan" stands for "not a number". This is happening because you have declared the variables characterSymbols and passwordLength without giving them an initial value.
You must initialize any variable before you use it - if you don't then you will have undetermined behavior. For example:
int x;
int y;
int z = x + y;
There is no way to predict what z will be equal to here because we don't know what x or y are equal to. In the same way, your code should be something like:
int characterSymbols = 10; //or whatever you want the initial value to be
...
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
In this way, numeratorFactorial will have a valid value.
It appears you think you are declaring "equations" when you are actually declaring variables. You write:
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
But characterSymbols isn't defined, only "declared". characterSymbols is declared above it, but it doesn't have a value... yet. Later on you use cin to get a value into it, but when you first declare numeratorFactorial you can't simply expect the program to insert the value into numeratorFactorial when characterSymbols changes.
Some definitions are probably in order: The statement double numeratorFactorial = some_value; creates a variable named numeratorFactorial and uses some_value to fill that variable immediately. What you want is a function, a logical statement that you can "pass values" to so values are generated when you need them. For example, for your numerator factorial:
double numeratorFactorial(double characterSymbols) {
return (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
}
int main() {
std::cout << "Numerator Factorial test: " << numeratorFactorial(5.0) << std::endl;
}
Note that you cannot declare a function within the main function.
This sort of thing is programming fundamentals, and it seems like you are trying to run before you've learned to walk. Get a good book like C++ Primer and pace yourself.