So I have some code that is supposed to be giving me the points on a parabola but the problem is that when I square the number when it is a negative it gives me a negative back which wont work.
#include "TileClass.h"
//#include <cmath> included in other header
// Original equation y=-x^2+4
void Tile::Loc() {
for (int a = -2; a < 3; a = a + 1) {
cout << "--- " << a << endl;
cout << "Pw" << (a << 2) << endl;
cout << ((a << 2) + 4) << endl;
}
}
output
--- -2
Pw-8
-4
--- -1
Pw-4
0
--- 0
Pw0
4
--- 1
Pw4
8
--- 2
Pw8
12
The C++ operator << is not the square operator. It is the bitshift operator.
Try
-(a*a)+4
instead
The express a<<2 will shift each bit of a to left by 2, which means a*4
And if you want to get the square of a, you had better use a*a.
it doesn't look like you're squaring. You're left shifting the binary value which is essentially the same as multiplying by 2 per left shift. So when a = -2, doing (a << 2) should result in -8 being displayed. What you are looking for is the pow() function found in the cmath library which should be used like this pow(a, 2);
Related
I'm not very familiar with bit operators and I have this use case : when we use the left shift operator << in C++ the number will be shifted and 0 will be placed at the right of number, I want to place 1 and not zero at the right.
I mean if I have a number 00000000 and I make << 3 the result need to be 00000111 and not 0 !
Simple approach is to left shift 1 by the number of bits you want set and then subtract 1
(1 << n) - 1
E.g.
cout << (1 << 2) - 1 << '\n'; // prints 3
cout << (1 << 3) - 1 << '\n'; // prints 7
cout << (1 << 4) - 1 << '\n'; // prints 15
cout << (1 << 5) - 1 << '\n'; // prints 31
But note this only works if n is less than the number of bits in an integer. Otherwise it's undefined behaviour.
Here's a solution that works on any number:
int one_shift(int val, int n) {
return ~(~0 << n) | (val << n);
}
Breakdown:
~0 evaluates to 0xFFFFFFFF e.g. all 1's
~0 << n shifts 0xFFFFFFFF by N places, resulting in a number with N zeroes on the end
~(~0 << n) flips all these bits, resulting in a number with only the last N bits set
| (val << n) then does a regular left shift on our original number by N places, and sets the last N bits by oring it with our other value
Also, here's a version that works on any integer type:
template<typename T>
T one_shift(T val, int n) {
return ~(~static_cast<T>(0) << n) | (val << n);
}
Then that's not what a left shift is.
You will have to set those bits to 1 yourself.
I'm trying a lab exercise which wants user to input a 2 4-digit integer. Then the program will extract all the numbers in the 4-digit integer and use the number to do an arithmetic calculation just like the image link below.
Arithmetic Calculation with 2 4-digit integer
However, the objective for this lab exercise is not to allow me myself, to use a for loop to obtain the result.
For instance, when i want to obtain the last number of the 4 digit integer, I could easily do it by using this.
int firstDigit = firstNo % 10; //i will get 4 if the integer is 1234
int secondDigit = secondNo % 10; //i will get 8 if the integer is 5678
And of course table formatting is nothing to worry about before getting the logic right. Next is a very simple calculation of the numbers using the digit i obtain from the above.
int addfirstNumbers = firstDigit + secondDigit;
int minusfirstNumbers = firstDigit - secondDigit;
int multiplefirstNumbers = firstDigit * secondDigit;
int modfirstNumbers = firstDigit % secondDigit;
double divfirstNumbers = firstDigit / secondDigit;
cout << "add: " << addfirstNumbers << endl
<< "minus " << minusfirstNumbers << endl
<< "multipile " << multiplefirstNumbers << endl
<< "remainder " << modfirstNumbers << endl
<< "division " << divfirstNumbers << endl;
I do understand forloop can make my life easier. But i'm just trying out the long method before trying out the shorter way which is forloop.
But even before i proceed, I'm still unable to extract out the other digit from this 4 digit integer.
Like Mike Vine mentioned in the comments, you can do integer division before taking the modulo.
#include <iostream>
int main(){
int x = 1234;
std::cout << (x/10)%10 << "\n";
}
#Output
3
Edit: This works for all places of a number. To find the nth value from the end, just keep adding 0s to the divisor. For example to find the 2nd from the last, you'd want to divide x by 100 instead.
You could simply do
int secondLastDigit = ((i - (i % 10)) % 100)) / 10;
For i=5678:
i % 10 (5678 % 10) equals 8
i - (i % 10) (5678 - 8) therefore equals 5670.
(i - (i % 10)) % 100 (5670 % 100) equals 70
Finally (i - (i % 10)) % 100) / 10 (70 / 10) = 7
This is pretty simple, just use the modulus operator on the number for 100(num%100), getting the last two digits that way, and then divide that result by ten, and store the digit in an int (so the decimal is properly truncated.)
I am writing a backward elimination algorithm. At each iteration I need to eliminate some coefficients from a column of a SparseMatrix and update the other non zero ones.
However, changing a reference to a coefficient to zero does not deallocate it, so the number of non zero coefficients is the same. How do I delete the reference? I tried with makeCompressed() to no avail and pruned is not known by the compiler.
Basic code below.
How can I solve this problem?
#include <Eigen/SparseCore>
void nukeit(){
Eigen::SparseMatrix<double> A(4, 3);
cout << "non zeros of empty: " << A.nonZeros() << "\n" << endl;
A.insert(0, 0) = 1;
A.insert(2, 1) = 5;
cout << "non zeros are two: " << A.nonZeros() << "\n" << endl;
A.coeffRef(0, 0) = 0;
cout << "non zeros should be one but it's 2: " << A.nonZeros() << "\n" << endl;
cout << "However the matrix has only one non zero element\n" << A << endl;
}
Output
non zeros of empty: 0
non zeros are two: 2
non zeros should be one but it's 2: 2
However the matrix has only one non zero element
0 0 0
0 0 0
0 5 0
0 0 0
After setting some of the coefficients of the current column to zero, you can explicitly remove them by calling A.prune(0.0). See the respective doc.
However, be aware that this will trigger a costly memory copy of the remaining column entries. With sparse matrices, we usually never work in-place.
In C++, an octal number is defined by preceeding it with a 0, example:
01 = 1
010 = 8
014 = 12
So I was experimenting how working with Base 8 in c++ works, and tried adding to it with a loop, like so:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << base8Number << '\n';
}
And apparently, C++ doesn't like working with octal numbers, the output I got is as follows:
1
3
6
10
15
21
28
36
The most obvious reason I know it's not working in Base 8, is the 28 output as a result, since the 8 number isn't used in Base 8.
So, my question: Can you work with Base 8 in c++, or is it just meant to be used as a constant, and if you can work with Base 8 in c++, how do you do it?
So first, let's remember that when we print numbers the way you're doing, they will be shown in decimal.
Now, let's rewrite your code without octal:
int base10Number = 0;
for (int i = 1; i < 9; i+=1)
{
base10Number += i;
cout << base10Number << '\n';
}
So let's now look at what your code is actually doing:
cout << 1 << "\n"; // 1
cout << 1 + 2 << "\n"; // 3
cout << 1 + 2 + 3 << "\n"; // 6
cout << 1 + 2 + 3 + 4 << "\n"; // 10
....
Which is what you're seeing. So no, there is no problem with how octal works in c++.
If you'd like you can use std::oct to tell std::cout to use octal printing. For example:
int main() {
std::cout << std::oct << 25 << "\n"; // Outputs: 31
}
Remember that "base" is a property of number representation, not the number itself. If you've got enough pegs to put one on each finger, then that is the same number of pegs regardless of whether you write 10, 012 0xA, or anything else.
Your code computes the numbers which would be shown in base 10 as 1, 3, 6, 10, 15, etc. You output them in base 10. To output them in base 8 use:
std::cout << std::oct << base8Number << std::endl;
There are a couple of things going on here.
Intrinsically, your computer operates in binary (base 2). When you do something like int foo = 10;, you are expressing the number 10 in decimal form because it's convenient for you to read it that way, but in the end the computer will still store it using binary, e.g. 1010.
If you were to use an octal literal (e.g. 012), then as far as the computer's concerned that's still just a 1010 binary constant - the only thing that's changed is its representation in the source code.
Finally, the last thing to realise is that the computer will by default output integers in base 10, because that's what's easy for people to read. It's still outputting the number 1010, just using the decimal representation of it.
Given all of the above, your code is entirely equivalent to doing the following, which you can verify for yourself produces the same output without using any octal:
int num = 0;
for (int i = 1; i < 9; i += 1) // Constants the same, just changed from octal representation to decimal.
{
num += i;
cout << num << '\n'; // Outputs in decimal, as with original program.
}
To get what you expect, try using the oct modifier:
int base8Number = 00;
for (int i = 01; i < 011; i+=01)
{
base8Number += i;
cout << oct << base8Number << '\n';
// ^--Here. Explicitly requests octal output.
}
This then explicitly requests that the computer output the values using octal.
Here is a C++ program I see today:
for (int i = 0; i < LEVELS; ++i)
{
int pyr_rows = rows >> i; // what is the usage of >> i here ?
int pyr_cols = cols >> i; // why we what to use it in this way.
depths_curr_[i].create (pyr_rows, pyr_cols);
}
What I am curious about is the usage of operator >> here. I tried a simple program and type the results:
int rows = 5;
int cols = 3;
for (int i=0; i<5; i++)
{
int pyr_rows = rows >> i;
std::cout << "current i is:" << i << std::endl;
std::cout << "pyr_rows is: " << pyr_rows << std::endl << std::endl;
int pyr_cols = cols >> i;
std::cout << "current i is:" << i << std::endl;
std::cout << "pyr_cols is: " << pyr_cols << std::endl << std::endl;
}
And the result is like this:
current i is:0
pyr_rows is: 5
current i is:0
pyr_cols is: 3
current i is:1
pyr_rows is: 2 // from now on
// the outputs of pyr_rows and pyr_cols are weird to me
current i is:1
pyr_cols is: 1
current i is:2
pyr_rows is: 1
current i is:2
pyr_cols is: 0
current i is:3
pyr_rows is: 0
current i is:3
pyr_cols is: 0
current i is:4
pyr_rows is: 0
current i is:4
pyr_cols is: 0
Why the output is like this? Can anyone explain it? And why we want to use this in this way? Any situation we prefer to do it?
It's not the "extraction operator", it's the right-shift operator, which is what >> meant before C++ started inventing crazy ways to overload it. I'm guessing from the pyr that this is pyramidal image processing? The idea is that every time i increases by one, the number of rows and columns in the pyramid are halved. That's because a right shift by i is basically a division (rounding down) by 2^i.
In the case you've outlined, >> stands for the right shift operator. If you consider an integer written in binary form:
01101 = 13
The >> i operator will make the bits above be shifted towards the right i times. So when i = 2, the above would result in:
00011 = 3
This is useful to efficiently divide integers by powers of 2. The result ends up rounded down, so 3 >> 1 equals 1, but -3 >> 1 equals -2.
This is the arithmetic shift, which means the leading bit gets padded, so that negative numbers can remain negative after the shift (leading bit 1). Some languages also have the >>> operator for the logical shift, which always pads the leading bits with zeroes.
It is not an "extraction operator", it is the original bitwise shift (right) operator, that was in C before anyone had even considered making a C++ language. It is now being used as an operator for files to input and output.
int x = 4;
int y = 1;
cout << (x >> y) << endl;
will produce 4 shifted right 1 bit, which should show the value 2.