fork download
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdbool.h>
  4. #include <string>
  5.  
  6. struct dbit {
  7. bool bit1;
  8. bool bit2;
  9. };
  10.  
  11. dbit BinaryAdd(bool num1, bool num2) {
  12. dbit ret;
  13. bool store;
  14. bool carry;
  15.  
  16. //if statements for each possibility
  17. if(num1 == 1 && num2 == 1) { // 1 + 1
  18. store = 0;
  19. carry = 1; //carry the 1 over to the next digit
  20. }
  21.  
  22. if(num1 == 0 && num2 == 0) { // 0 + 0
  23. store = 0;
  24. carry = 0; //nothing
  25. }
  26.  
  27. if(num1 == 1 && num2 == 0) { //1 + 0
  28. store = 1; //just 1
  29. carry = 0;
  30. }
  31.  
  32. if(num1 == 0 && num2 == 1) {//0 + 1
  33. store = 1; //just 1
  34. carry = 0;
  35. }
  36.  
  37. //put values into struct because we can't return two variables from a function
  38. ret.bit1 = store;
  39. ret.bit2 = carry;
  40.  
  41. //and return that value containing the store and carry
  42. return ret;
  43. }
  44.  
  45. int main() {
  46. //create variables for input/output
  47. bool input_bit1;
  48. bool input_bit2;
  49. dbit output;
  50.  
  51. //write title
  52. std::cout << "Binary Calculator\n";
  53.  
  54. //send user message to collect input
  55. std::cout << "Use the 'input' tab to choose which single-digit binary numbers to add\n";
  56. std::cin >> input_bit1;
  57. std::cin >> input_bit2;
  58.  
  59. //run function
  60. output = BinaryAdd(input_bit1, input_bit2);
  61.  
  62. //write output
  63. std::cout << "Well, if we add " << std::to_string(input_bit1) << " and " << std::to_string(input_bit2) << ", we get " << std::to_string(output.bit2) << std::to_string(output.bit1);
  64.  
  65. //close program
  66. return 0;
  67. }
Success #stdin #stdout 0s 15240KB
stdin
1
1
stdout
Binary Calculator
Use the 'input' tab to choose which single-digit binary numbers to add
Well, if we add 1 and 1, we get 10