Advertisement
programusy

Untitled

Mar 2nd, 2023
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. bool isPrime(int num) {
  7. if (num <= 1) {
  8. return false;
  9. }
  10. for (int i = 2; i <= num / 2; i++) {
  11. if (num % i == 0) {
  12. return false;
  13. }
  14. }
  15. return true;
  16. }
  17.  
  18. int main() {
  19. // Open the file
  20. std::ifstream inputFile("/Users/jacobe/Desktop/plik.txt");
  21. if (!inputFile.is_open()) {
  22. std::cerr << "Failed to open file" << std::endl;
  23. return 1;
  24. }
  25.  
  26. // Read the numbers into a vector
  27. std::vector<int> numbers;
  28. int num;
  29. while (inputFile >> num) {
  30. numbers.push_back(num);
  31. }
  32.  
  33. // Calculate the sum and average
  34. int sum = 0;
  35. for (int num : numbers) {
  36. sum += num;
  37. }
  38. double average = static_cast<double>(sum) / numbers.size();
  39.  
  40. // Calculate the median
  41. std::sort(numbers.begin(), numbers.end());
  42. int median;
  43. if (numbers.size() % 2 == 0) {
  44. median = (numbers[numbers.size() / 2 - 1] + numbers[numbers.size() / 2]) / 2;
  45. } else {
  46. median = numbers[numbers.size() / 2];
  47. }
  48.  
  49.  
  50. int numPositives = 0;
  51. int numNegatives = 0;
  52. for (int num : numbers) {
  53. if (num > 0) {
  54. numPositives++;
  55. } else if (num < 0) {
  56. numNegatives++;
  57. }
  58. }
  59.  
  60.  
  61. std::cout << "Suma: " << sum << std::endl;
  62. std::cout << "Średnia: " << average << std::endl;
  63. std::cout << "Mediana: " << median << std::endl;
  64. std::cout << "Liczby pozytywne: " << numPositives << std::endl;
  65. std::cout << "Liczby negatywne: " << numNegatives << std::endl;
  66. std::cout << "Liczby pierwsze: ";
  67. for (int num : numbers) {
  68. if (isPrime(num)) {
  69. std::cout << num << " ";
  70. }
  71. }
  72. std::cout << std::endl;
  73.  
  74.  
  75. inputFile.close();
  76.  
  77. return 0;
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement