alansam

Format array of floating points [blended C/C++]

Jun 1st, 2022 (edited)
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. #ifdef __cplusplus
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <array>
  5. #else
  6. #include <stdio.h>
  7. #endif
  8.  
  9. int main() {
  10. #ifdef __cplusplus
  11.     auto a = std::array {
  12.         10.67, 68.43, 56.55, 92.60, 90.65,
  13.     };
  14. #else
  15.     double a[] = {
  16.         10.67, 68.43, 56.55, 92.60, 90.65,
  17.     };
  18.     size_t const a_sz = sizeof(a) / sizeof(*a);
  19. #endif
  20.  
  21. #ifdef __cplusplus
  22.     std::cout << "array elements are:\n";
  23.     std::cout << std::fixed
  24.               << std::setprecision(2);
  25.     for (auto d : a) {
  26.         std::cout << std::setw(8) << d;
  27.     }
  28.     std::cout << std::endl;
  29. #else
  30.     printf("array elements are:\n");
  31.  
  32.     for (size_t i = 0; i < a_sz; i++) {
  33.         printf("%8.2f", a[i]);
  34.     }
  35.     putchar('\n');
  36. #endif
  37.  
  38.     return 0;
  39. }
  40.  
Add Comment
Please, Sign In to add comment