fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. string binaryExpansion(int p, int q) {
  6. string result = "0.";
  7.  
  8. // q musi być potęgą 2
  9. if ((q & (q - 1)) != 0) {
  10. return "Blad: mianownik nie jest potega dwojki.";
  11. }
  12.  
  13. // liczba bitów = log2(q)
  14. int k = 0;
  15. int t = q;
  16. while (t > 1) {
  17. t >>= 1;
  18. k++;
  19. }
  20.  
  21. for (int i = 0; i < k; i++) {
  22. p *= 2;
  23. if (p >= q) {
  24. result += '1';
  25. p -= q;
  26. } else {
  27. result += '0';
  28. }
  29. }
  30.  
  31. return result;
  32. }
  33.  
  34. int main() {
  35. // Zdefiniowany ułamek:
  36. int p = 7; // licznik
  37. int q = 8; // mianownik (potęga 2)
  38.  
  39. cout << "Ułamek: " << p << "/" << q << endl;
  40. cout << "Rozwiniecie binarne: " << binaryExpansion(p, q) << endl;
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5320KB
stdin
1 16
stdout
Ułamek: 7/8
Rozwiniecie binarne: 0.111