Напишите програму которая считает среднее арифметическое в файлах
Ответы
Ответ:
Python:
```
# open the file
with open("filename.txt", "r") as file:
# read the lines and convert them to numbers
numbers = [float(line.strip()) for line in file.readlines()]
# calculate the average
average = sum(numbers) / len(numbers)
# print the result
print("The average is:", average)
```
C++:
```
#include <iostream>
#include <fstream>
#include <vector>
#include <numeric>
int main() {
// open the file
std::ifstream file("filename.txt");
if (!file) {
std::cerr << "Error opening file" << std::endl;
return 1;
}
// read the numbers into a vector
std::vector<double> numbers;
double number;
while (file >> number) {
numbers.push_back(number);
}
// calculate the average
double average = std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
// print the result
std::cout << "The average is: " << average << std::endl;
return 0;
}
```
Scratch:
1. Create a new project in Scratch
2. Create a "when flag clicked" block from the Events menu
3. Create a "set variable" block from the Variables menu and name it "total"
4. Create a "set variable" block from the Variables menu and name it "count"
5. Create a "repeat until" block from the Control menu
6. Inside the "repeat until" block, create a "ask [] and wait" block from the Sensing menu and ask the user to enter a number, then drag a "set variable" block from the Variables menu and set it to the input
7. Inside the "repeat until" block, create a "change [] by []" block from the Variables menu and change "total" by the input variable you just created
8. Inside the "repeat until" block, create a "change [] by []" block from the Variables menu and change "count" by 1
9. After the "repeat until" block, create a "set variable" block from the Variables menu and name it "average"
10. Create a "set variable" block from the Variables menu and set "average" to "total" divided by "count"
11. Create a "say []" block from the Looks menu and set it to "The average is [average]"