I'm going to show you two ways to do this.
We know that for each student, we want to write
that student's total into an array and return it. We
also know exactly how big we want the array to
be because we want one for each student. So I
want numStudents items in my array. Now, for all of
the student from the 0 student to the last student
Going up one at a time. I want to fill that student's
spot in the array of totals with that
student's total. I already have a method that calculates
this. So, I can use totalForStudent. And then,
when I've done that for all of the students,
I can return the totals. Looks like I forgot to
call it totals. Let's check that it works. I'll run
the tester, and it looks like it's got what I
expecting. Now, we could use nested for loops. I'll still
want all of my totals, and I'll still want to
return them, but let's think about solving this problem for
just one student, for each topic, starting with the first
one. And we going up to the number of topics,
one at a time. I'll add the score
for that topic to that student's total, let's say
for now I'm thinking about student 1. To
calculate total for student 1, I'll start at 0
and for each topic And want to add
that student's grade, in that topic. Then, once I
have the student total in my larger array
totals, I'll set the total for that student to
be the student total that I just calculated.
So this is what I do for one student.
And now, I want to do that for every single
student. So that all of the spaces in total
gets filled, so I will indent that a little
bit and now for each student starting with the
zeroth one so we don't need this line anymore
I will go up to the number of students
one at a time. I will do all of these steps. So
now the inter-loop is calculating the student totals and the outer loop is
storing the student totals in totals. So now we're fix up syntax errors. And
this way should work just like the last one. I'll
run it to make sure and it looks like it's
still good. Hopefully the number of values you see here.
Makes it obvious why it would be be nice as
a teacher, have a computer do this for you.
Les voy a mostrar dos formas de hacer esto.
Sabemos que para cada estudiante, queremos escribir
el total de ese estudiante en un «array» y devolverlo. También
sabemos exactamente qué tan grande queremos que sea el «array»
porque queremos uno para cada estudiante. Así que
quiero los artículos «numStudents» en mi «array» Ahora, para todos
los estudiantes, a partir del estudiante «0» hasta el último estudiante,
subiendo de uno en uno. Quiero llenar el espacio de ese estudiante
en el «array» de totales con el
total de ese estudiante. Ya tengo un método que calcula
esto. Así que puedo usar «totalForStudent». Y luego,
cuando lo haya hecho para todos los estudiantes,
puedo devolver los totales. Parece que se me olvidó
llamarlo «totals». Revisemos si funciona. Ejecutaré este
probador, parece que obtuvo lo que
esperaba. Ahora, también podríamos utilizar bucles «for» anidados. Todavía
quiero todos mis totales, y todavía quiero
devolverlos, pero vamos a pensar en la solución de este problema para
sólo un estudiante. Para cada tema, empezando con el
primero, y luego subiendo hasta el número de temas,
uno a la vez. Voy a añadir la calificación
para ese tema al total de ese estudiante, digamos
que por ahora estoy pensando en el estudiante 1. Para
calcular el total para estudiante 1, voy a empezar en 0
y para cada tema quiero agregar
la calificación de ese estudiante, en ese tema. Luego, una vez que
tengo el total del estudiante, en mi «array» grande de
totales, voy a establecer el total de ese estudiante para que
sea el total del estudiante que recién calculé.
Así que, esto es lo que hago para un estudiante.
Y ahora, quiero hacer eso para cada uno
de los estudiantes. Así que todos los espacios en los totales
se llenan. Así que voy a ponerle margen a eso
y ahora para cada alumno, a partir del número
cero uno, así que ya no necesito esta línea,
voy a ir hasta el número de estudiantes
uno a la vez. Voy a hacer todos estos pasos. Entonces,
ahora el bucle interior está calculando los totales de los estudiantes y el bucle externo está
almacenando los totales de los estudiantes en los totales. Ahora voy a corregir mis errores de sintaxis. Y
de esta manera debería funcionar igual que el anterior. Voy a
ejecutarlo para asegurarme. Y parece que todavía
está bien. Esperemos que el número de valores que ven aquí
haga evidente por qué sería bueno como
maestro que una computadora haga esto por ustedes.
Je vais vous montrer
deux façons de le faire.
Nous savons que pour
chaque étudiant,
nous voulons écrire le total
dans un tableau
et le renvoyer.
Nous savons également exactement
quelle envergure le tableau doit avoir
parce que nous voulons un
pour chaque étudiant.
Je veux donc des éléments
de numStudents dans mon tableau.
Pour tous les étudiants
de l'étudiant 0 au dernier étudiant
en remontant un à la fois.
Je veux remplir la place
de cet étudiant
dans le tableau des totaux
avec le total de cet étudiant.
J'ai déjà une méthode qui calcule cela.
Donc, je peux utiliser totalForStudent.
Et quand je l'ai fait
pour tous les étudiants,
je peux renvoyer les totaux.
On dirait que j'ai oublié
de l'appeler totals.
Vérifions que ça fonctionne.
Je lance le testeur,
et on dirait que ça a donné
ce à quoi je m'attendais.
Nous pourrions aussi
utiliser des boucles imbriquées.
Je veux toujours tous mes totaux
et je veux aussi les renvoyer,
mais réfléchissons à la résolution de
ce problème pour un seul étudiant,
pour chaque sujet, en
commençant par le premier,
et nous remontons le nombre
de sujets, un à la fois.
J'ajouterai la note pour
ce sujet au total de cet étudiant.
Disons que pour l'instant
je pense à l'étudiant 1.
Pour calculer le total
pour l'étudiant 1,
je commence à 0
et pour chaque sujet,
je veux ajouter la note de
cet étudiant,
dans ce sujet.
Une fois que j'ai le total de l'étudiant
dans mon tableau plus large de totaux,
je définirai le total pour cet étudiant
comme étant le total des étudiants
que je viens de calculer.
Donc, voici ce que je fais
pour un étudiant
et maintenant, je veux le faire
pour chaque étudiant
pour que tous les espaces
soient remplis.
Je vais indenter ça un peu,
et maintenant pour chaque étudiant,
commençant par le 0,
nous n'avons plus besoin de cette ligne,
je remonte le nombre d'étudiants
un à la fois.
Je suis toutes ces étapes.
La boucle interne, calcule
les totaux des étudiants
et la boucle externe stocke les totaux
des étudiants dans totals.
J'en profite pour corriger
mes erreurs de syntaxe.
Cette approche devrait marcher
comme la dernière.
Je la lancerai pour m'en assurer
et ça semble toujours bon.
J'espère que vous voyez avec
ce nombre de valeurs à quel
point ce serait facile pour un professeur
d'avoir un ordinateur qui le fait à sa place.
2つの実装方法を紹介します
まずそれぞれの生徒の合計を
配列に入れて返すことです
配列の大きさも分かっています
各生徒に1つずつ必要ですね
そこでnumStudentsを使います
生徒ゼロから最後の生徒までです
そしてインクリメントします
次にtotalsの[student]に
その生徒の合計を入れます
これを計算するメソッドはすでにあります
totalforStudentを使いましょう
すべての生徒の分を行ったら
合計を返すことができます
書き忘れたtotalsを入れてから確認します
正しい結果が得られたようですね
今度はネストしたforループを使ってみます
すべての合計を出し
それらを返すということは同じです
まず1人の生徒分を考えます
最初のトピックから最後まで指定し
それぞれをインクリメントします
その生徒の合計に
トピックのスコアを足していきます
ここでは生徒1のことを考えましょう
生徒1の合計を計算するにはゼロから開始し
それぞれのトピックに
その生徒のスコアを加えていきます
そしてより大きい合計の配列に
その生徒の合計が入ったら
今計算したその生徒の合計が
その生徒の合計になるように指定します
これが1人の生徒の分です
全員の分同じように作成し
それぞれの合計を出します
少しインデントします
それぞれの生徒をゼロ番目から始めます
この行はもう必要ありません
生徒数を1ずつ増やしていきます
これらのステップをすべて行います
この内側のループはその生徒の合計を計算し
外側のループは
totalsにその生徒の合計を保存します
シンタックスエラーを修正し
これでうまくいくはずです
確認のために実行します 大丈夫ですね
ここに表示された数値の数を見ると
コンピュータで作業することの利点が分かりますね
이 문제를 풀 수 있는 방법은 두 가지가 있습니다.
각각의 학생들 점수를 알고 있으니, 그 학생들의
점수를 배열 안에 저장하고 리턴해야 합니다. 또한
배열이 얼마나 커야 하는지도 알고 있습니다. 왜냐하면
학생들이 몇 명인지 알고 있기 때문입니다.
배열에 numStudents를 넣습니다. 이제 모든
학생들을 위해서 0에서 numStudents까지 반복문을
실행합니다. 그 학생의
인덱스에 그 학생의
총점을 저장합니다. 총점을 계산해주는 메소드가
있으니, totalForStudent를 사용합니다. 그런 후에,
모든 학생들에게 똑같이 하면,
totals를 리턴 할 수 있습니다. 변수 명을
totals로 선언하는 것을 잊은 모양입니다.
테스터를 실행해보겠습니다. 제가 예상하는 결과와
맞는 걸로 보입니다. 이제 중첩된 for문을 이용해서 문제를 풀 수
있습니다. totals는 아직 필요하고
리턴하기도 해야 합니다. 하지만 이 문제를 우선
한 학생에게만 적용해 보겠습니다. 첫 번째
주제로 시작해서, numberOfTopics까지
갑니다. 그 주제를
학생의 총점에 더해보겠습니다. 예를 들어,
학생 1로 하겠습니다. 학생 1의
총점을 구하기 위해서, 0으로 시작하고
각각의 주제에 그 학생의
성적을 더합니다. 이제 그 학생의
성적이 이 배열 안에 저장이
되면, 그 학생의 요소에 방금
계산한 값을 저장하겠습니다.
이는 한 학생의 성적을 계산할
때의 코드입니다. 이제 모든 학생을
계산해야 합니다. totals의
모든 요소를 다 채우기
위해서, for문을 하나 더 만들겠습니다.
0번째 학생부터 시작해서, numStudents
까지 반복합니다.
이 코드를 실행하면
학생들의 총점을 계산합니다. 밖에 있는
for문은 학생들의 총점을 totals안에 저장합니다.
문법 오류가 있는지 보고, 전에 실행한 프로그램과 똑같이
작동합니다. 실행을 해보니 잘
되는 걸로 보입니다. 여기에 보이는 값들의
개수를 보면, 컴퓨터가 해주는 것이 얼마나
편한지 알 수 있을 겁니다.