I have prompted the user to enter in two numbers; however, my programs wants to output the even numbers between those two numbers. Suppose number one is higher then number 2. For instance
number1: 10
number2: 0
I want number 1 to be the least value and number 2 to be the highest. How do I fix this issue?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//Tell user to enter a number
cout<<"\n\tEnter in two numbers: ";
cin>>number1;
cout<< " " ;
cin>>number2;
//whle loop
if (number1>number2)
{
cout<<"number 1 will now be ";
number2=number1;
cout<<number1;
cout<<"\nNumber2 will be " << number2;
}
you need a temp variable to hold one of the numbers
Not true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
int main(int argc, char* argv[]) {
//bitwise swap
int a = 10;
int b = 20;
a ^= b;
b ^= a;
a ^= b;
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
std::cin.get();
return 0;
}
I disagree. Bitwise operations generally are compiled into more efficient machine code, and additional variables means more overhead.
Not that it matters, since this is a beginners thread, and it's not 1980.
What if we don’t do this “XOR trick”, and just swap the contents using a temporary variable?
...
Lo and behold, now it runs at 7 cycles / pixel (almost twice as fast), and the inner loop is two memory reads and two writes
Most modern compilers can optimize away the temporary variable in the naive swap, in which case the naive swap uses the same amount of memory and the same number of registers as the XOR swap and is at least as fast, and often faster. The XOR swap is also much less readable and completely opaque to anyone unfamiliar with the technique.
On modern CPU architectures, the XOR technique is considerably slower than using a temporary variable to do swapping. One reason is that modern CPUs strive to execute instructions in parallel via instruction pipelines. In the XOR technique, the inputs to each operation depend on the results of the previous operation, so they must be executed in strictly sequential order. If efficiency is of tremendous concern, it is advised to test the speeds of both the XOR technique and temporary variable swapping on the target architecture.
The compiler has no idea what the hell you are intending. Using the rather more standard “char t = a; a = b; b = t;” the compiler knows what you are doing and is able to optimise it. Your compiler is almost certainly smarter than you are, and might know about things such as swap opcodes that are supported by your CPU, or even more highly efficient implementations that might be based on your particular architecture