§ 2.2. Одномерные массивы целых чисел ГДЗ по Информатике 9 класс. Босова.
Напишите программу, которая вычисляет среднюю за неделю температуру воздуха. Исходные данные вводятся с клавиатуры.
Пример входных данных | Пример выходных данных |
Введите температуру Понедельник>>12 Вторник>>10 Среда>>16 Четверг>>18 Пятница>>17 Суббота>>16 Воскресенье>>14 |
Средняя температура за неделю: 14.71 |
Ответ
program temperatuta;
var
а: array [1..7] of integer; // Исходные данные
i: integer; // Счетчик цикла
s: integer; // Промежуточная величина
st: real; // Результат
const b: array [1..7] of string = (‘Понедельник’, ‘Вторник’, ‘Среда’, ‘Четверг’, ‘Пятница’, ‘Суббота’, ‘Воскресенье’);
begin
writeln (‘Введите температуру’);
for i:= 1 to 7 do
begin
writeln (b[i], ‘>>’);
readln (a[i])
end;
s:= 0;
for i:=1 to 7 do
s:=s+a[i];
st:=s/7;
writeln (‘Средняя температура за неделю:’, st:4:2);
end.
I am a new coder and was wondering if anybody could tell me what was going wrong with the code below. I was trying to answer the question below and have been stuck. If anybody could help that would be awesome.
Write a program that asks the user to enter the high temperature for
each day of one week. Store the temperatures in a list. Once
completed, output all temperatures that have been stored into the list
as a formatted table along with the average temperature for the week.
week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print "Day" + (" "*12) + "High Temperature"
print "-"*30
temperature = []
temp = 0
spaces = 0
for i in range (len(week_days)):
temp_input = input ("Enter the temperature for" +week_days[i]+str(":"))
temperature.append(temp_input)
spaces = 15-len(week_days[i])
print week_days[i]," "*spaces,temperature[i]
avg= 0
list_sum = 0
for i in range (len(temperature)):
avg = ((list_sum + temperature[i])-15)/7
avg = int((avg*100) + 0.5)/100
print "The average temperature for this week is", average
EDIT: Sorry guys I fixed the error, but now my average only seems to be printing 3. Any suggestions?
asked Nov 6, 2014 at 0:35
2
-
Sum is in-built function, it’s used to calculate the the sum of elements inside a list. not sure what you wanna calculate, but if you wanna calculate the sum of temperatures, you can use it this way
sum(temperature)
-
Try to add convert inputs to int to apply math operations
Would be better if you can give more details. But your code should look like:
week_days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print "Day" + (" "*12) + "High Temperature"
print "-"*30
temperature = []
temp = 0
spaces = 0
for i,x in enumerate(week_days):
temp_input = input ("Enter the temperature for" +x+str(":"))
temperature.append(int(temp_input))
spaces = 15-len(x)
print x," "*spaces,temperature[i]
avg= sum(temperature)//len(week_days)
print "The average temperature for this week is", avg
answered Nov 6, 2014 at 0:47
0
Use a dict with str.format, you can pass the keys as args and use Format Specification Mini-Language to output the data any way you want:
week_days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
# get user input for each day and convert to ints
temps = map(int,[raw_input("Enter temp for {}".format(week_days[i])) for i in xrange(7)])
# make dict with days as keys and temps as values
zipped = dict(zip(week_days,temps))
print("Daily Temps: Monday: {Mon} Tuesday: {Tue} Wednesday: {Wed}"
" Thursday: {Thu} Friday: {Fri} Saturday: {Sat} Sunday: {Sun}".format(**zipped))
print("Average Temp for the week: {:.2f}".format(sum(temps) / 7.0))
answered Nov 6, 2014 at 0:55
You can write this following simple code:
day1 = input("enter mondays temp: ")
day2 = input("enter tuesdays temp: ")
day3 = input("enter wednesdays temp: ")
day4 = input("enter thursdays temp: ")
day5 = input("enter fridays temp: ")
day6 = input("enter saturdays temp: ")
day7 = input("enter sundays temp: ")
av = (day1+day2+day3+day4+day5+day6+day7) / 7
print("The average temperature is ",av)
jps
19.4k15 gold badges72 silver badges79 bronze badges
answered Oct 7, 2015 at 13:35
1
var
a: array[1..7] of string = (‘Понедельник’, ‘Вторник’, ‘Среда’, ‘Четверг’, ‘Пятница’, ‘Суббота’, ‘Воскресенье’);
av: real; i, t: integer;
begin
writeln(‘Введите температуру воздуха за неделю.’);
for i := 1 to 7 do
begin
write(a[i], ‘ -> ‘); readln(t); av := av + t;
end;
av := av / 7;
writeln(‘Средняя температура за неделю: ‘, av:0:2, ‘ град.’);
readln;
end.
поделиться знаниями или
запомнить страничку
- Все категории
-
экономические
43,662 -
гуманитарные
33,654 -
юридические
17,917 -
школьный раздел
611,978 -
разное
16,905
Популярное на сайте:
Как быстро выучить стихотворение наизусть? Запоминание стихов является стандартным заданием во многих школах.
Как научится читать по диагонали? Скорость чтения зависит от скорости восприятия каждого отдельного слова в тексте.
Как быстро и эффективно исправить почерк? Люди часто предполагают, что каллиграфия и почерк являются синонимами, но это не так.
Как научится говорить грамотно и правильно? Общение на хорошем, уверенном и естественном русском языке является достижимой целью.
0 / 0 / 0 Регистрация: 29.11.2020 Сообщений: 6 |
|
1 |
|
Написать программу, которая вычисляет среднюю (за неделю) температуру воздуха03.12.2020, 10:56. Показов 5569. Ответов 1
Доброе утро! Возникли сложности т.к эту задачу нужно решить с помощью массивов. Буду очень рад за помощь, есть 45 минут на написание( Написать программу, которая вычисляет среднюю (за неделю) температуру
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
03.12.2020, 10:56 |
1 |
FallingBoy 3 / 2 / 1 Регистрация: 01.12.2020 Сообщений: 16 |
||||
03.12.2020, 11:33 |
2 |
|||
Решение Возможно не самая лучшая реализация, но по крайней мере работает
1 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
03.12.2020, 11:33 |
2 |