Aquí hay un programa que debería imprimir el promedio de dos números. Ejecuta. No falla. Imprime una respuesta —y la respuesta es incorrecta. Dale cuatro y seis…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
1.1
Colaboración
Syllabus
Comprensión duradera (CRD-1): La incorporación de múltiples perspectivas a través de la colaboración mejora las innovaciones computacionales a medida que se desarrollan.
Objetivo de aprendizaje CRD-1.A: Explicar cómo las innovaciones computacionales se mejoran mediante la colaboración. [Habilidad 1.C]
CRD-1.A.1 Una innovación computacional incluye un programa como parte integral de su función.
CRD-1.A.2 Una innovación computacional puede ser física (p. ej., un automóvil autónomo), software computacional no físico (p. ej., software de edición de imágenes) o un concepto computacional no físico (p. ej., comercio electrónico).
CRD-1.A.3 La colaboración efectiva produce una innovación computacional que refleja la diversidad de talentos y perspectivas de quienes la diseñaron.
CRD-1.A.4 La colaboración que incluye diversas perspectivas ayuda a evitar sesgos en el desarrollo de innovaciones computacionales.
CRD-1.A.5 La consulta y la comunicación con los usuarios son aspectos importantes del desarrollo de innovaciones computacionales.
CRD-1.A.6 La información recopilada de posibles usuarios puede utilizarse para comprender el propósito de un programa desde diversas perspectivas y para desarrollar un programa que incorpore plenamente estas perspectivas.
Objetivo de aprendizaje CRD-1.B: Explicar cómo las innovaciones computacionales son desarrolladas por grupos de personas. [Habilidad 1.C]
CRD-1.B.1 Las herramientas en línea apoyan la colaboración al permitir que los programadores compartan e intercambien retroalimentación sobre ideas y documentos.
CRD-1.B.2 Modelos comunes como la programación en parejas existen para facilitar la colaboración.
Objetivo de aprendizaje CRD-1.C: Demostrar habilidades interpersonales efectivas durante la colaboración. [Habilidad 1.C]
CRD-1.C.1 Los equipos colaborativos efectivos practican habilidades interpersonales, incluidas, entre otras:
comunicación
construcción de consensos
resolución de conflictos
negociación
Fuente: College Board AP Course and Exam Description
English
A jigsaw in progress: collaboration and modular design piece the solution together
In 1999 NASA lost the Mars Climate Orbiter, a spacecraft that had cost well over a hundred million dollars. The code was not badly written. One team's software gave its numbers in US units, and another team's software read them as metric units. Each piece worked alone; the failure was between the people. This unit is about how programs are really made: by groups, for users, in repeated cycles, with errors found and fixed along the way.
Computing is a collaborative 协作 activity. Working in a team brings more perspectives 视角, catches more errors, and produces better programs than working alone. Good collaboration uses consensus building 达成共识, clear communication, and each member's strengths. Pair programming 结对编程 – two people at one computer, one typing and one reviewing – is a common practice. On the exam, you should be able to explain how collaboration improved a program (more ideas, fewer bugs 缺陷, wider testing 测试).
A computing innovation 计算创新 is anything new that has a program as an essential part. It can be physical (a self-driving car), software (a photo editor), or a concept (online shopping). When a question says "computing innovation", any of the three will do.
Why different people matter. People with different backgrounds notice different problems. A team that includes different perspectives is more likely to avoid bias 偏见, because someone in the room will ask "what about users like me?". Developers also talk to users 用户 directly: what users say helps the team understand what the program is for and who it must work for.
Skills and tools. Good teams practise communication, consensus building, conflict resolution 解决冲突 and negotiation 协商. Online tools such as shared documents and shared code stores let people give feedback from anywhere.
Worked example. Two students build a quiz app. Mei writes the scoring procedure while Tom reviews each line as she types; later Tom asks five classmates to try the app, and two of them find that a blank answer crashes it. How did collaboration help?
Tom reviews the code as it is typed (pair programming), which can catch errors early.
The classmates are users with different habits; their tests found a case neither programmer had thought of, the blank answer.
Each benefit is named and tied to the program: "more testers found the blank-answer crash" earns credit where "teamwork is good" does not.
Worked example: a disagreement. Two teammates disagree: Sara wants a timer on each quiz question, and Li says a timer will worry nervous users. Which is the best next step?
Sara and Li vote and the loser gives way: quick, but it ignores the users.
Each builds their own version and they never share it: the team splits.
They ask some users, then agree a rule together, for example a timer that users can turn off.
The third is consensus building: the decision comes from evidence, and both people accept it.
Comprensión duradera (CRD-2): Los desarrolladores crean e innovan mediante un proceso de diseño iterativo centrado en el usuario, que incorpora ciclos de implementación y retroalimentación, y que deja amplio margen para la experimentación y la asunción de riesgos.
Objetivo de aprendizaje CRD-2.A: Describir el propósito de una innovación computacional. [Habilidad 1.A]
CRD-2.A.1 El propósito de las innovaciones computacionales es resolver problemas o perseguir intereses a través de la expresión creativa.
CRD-2.A.2 La comprensión del propósito de una innovación computacional proporciona a los desarrolladores una mayor capacidad para crear dicha innovación.
Objetivo de aprendizaje CRD-2.B: Explicar cómo funciona un programa o un segmento de código. [Habilidad 4.A]
CRD-2.B.1 Un programa es un conjunto de instrucciones de programa que realiza una tarea específica cuando es ejecutado por una computadora. A menudo se hace referencia a un programa como software.
CRD-2.B.2 Un segmento de código es un conjunto de instrucciones de programa que forma parte de un programa.
CRD-2.B.3 Un programa debe funcionar correctamente ante una variedad de entradas y situaciones.
CRD-2.B.4 El comportamiento de un programa es la manera en que opera durante su ejecución y suele describirse según la interacción del usuario con él.
CRD-2.B.5 Un programa puede describirse de forma general indicando lo que hace, o con más detalle especificando tanto lo que hace el programa como cómo las instrucciones logran esa función.
Objetivo de aprendizaje CRD-2.C: Identificar la(s) entrada(s) de un programa. [Habilidad 3.A]
CRD-2.C.1 Las entradas del programa son datos enviados a una computadora para ser procesados por un programa. La entrada puede presentarse en diversas formas, como táctil, auditiva, visual o textual.
CRD-2.C.2 Un evento está asociado a una acción y suministra datos de entrada a un programa.
CRD-2.C.3 Los eventos pueden generarse al presionar una tecla, hacer clic con el mouse, iniciar un programa u ocurrir cualquier otra acción definida que afecte el flujo de ejecución.
CRD-2.C.4 Las entradas suelen afectar la salida producida por un programa.
CRD-2.C.5 En la programación basada en eventos, las instrucciones del programa se ejecutan cuando son activadas, en lugar de hacerlo mediante un flujo de control secuencial.
CRD-2.C.6 La entrada puede provenir de un usuario o de otros programas.
Objetivo de aprendizaje CRD-2.D: Identificar la(s) salida(s) producidas por un programa. [Habilidad 3.A]
CRD-2.D.1 Las salidas del programa son todos los datos enviados desde un programa a un dispositivo. La salida del programa puede presentarse en diversas formas, como táctil, auditiva, visual o textual.
CRD-2.D.2 La salida del programa generalmente se basa en la entrada del programa o en su estado previo (p. ej., valores internos).
Fuente: College Board AP Course and Exam Description
English
Every program is written for a purpose 目的 – it solves a problem or pursues an interest. A program takes input 输入, processes it, and produces output 输出. Inputs can come from a user, a device, a file, or another program; outputs can be visual, audible, textual, or a signal to a device. Being able to state a program's purpose, and describe its inputs and outputs clearly, is a core skill (and part of the Create performance task).
Some words the exam uses exactly:
A program 程序 (also called software 软件) is a collection of statements that does a task when a computer runs it. A code segment 代码段 is one part of a program.
A program's behavior 行为 is how it acts while it runs, usually described by how a user interacts with it.
Input and output can each be tactile 触觉的 (touch, vibration), audio, visual or text.
Output usually depends on the input, and it can also depend on prior state: values the program already holds.
You can describe a program broadly (what it does), or in more detail (what it does and how its statements do it). A written response usually needs the second.
Every program decomposes into input, processing, and outputEvery program follows the input-processing-output model
Worked example. A step-counter app reads movement from the phone's motion sensor, counts steps, and shows the day's total and a badge when the user reaches 10,000.
Ask
Answer
Purpose: why it exists
to help users stay active by tracking their walking
Function: what it does
counts steps and compares the total with a goal
Input
readings from the motion sensor
Output
the step total on screen; a badge at 10,000
The badge also shows prior state at work: the same step of input gives a badge only if the stored total has just reached the goal.
A common mistake is to give the function as the purpose: "it counts steps" says what the program does, not the problem it solves.
Explorar
Explorar el modelo entrada → procesamiento → salida
Recorrer el modelo IPO. Todo programa toma una entrada, realiza un procesamiento siguiendo sus instrucciones y luego produce una salida: rastrear un ejemplo de aplicación meteorológica a lo largo del proceso.
Comprensión perdurable (CRD-2): Los desarrolladores crean e innovan mediante un proceso de diseño iterativo centrado en el usuario, que incorpora ciclos de implementación y retroalimentación, y que deja amplio margen para la experimentación y la asunción de riesgos.
Objetivo de aprendizaje CRD-2.E: Desarrollar un programa utilizando un proceso de desarrollo. [Habilidad 1.B]
CRD-2.E.1 Un proceso de desarrollo puede ser ordenado e intencional, o tener una naturaleza exploratoria.
CRD-2.E.2 Existen múltiples procesos de desarrollo. Las siguientes fases se utilizan comúnmente al desarrollar un programa:
investigación y reflexión
diseño
prototipado
prueba
CRD-2.E.3 Un proceso de desarrollo iterativo requiere refinamiento y revisión basados en la retroalimentación, las pruebas o la reflexión a lo largo del proceso. Esto puede implicar volver a fases anteriores del proceso.
CRD-2.E.4 Un proceso de desarrollo incremental es aquel que divide el problema en partes más pequeñas y asegura que cada parte funcione correctamente antes de integrarla al conjunto completo.
Objetivo de aprendizaje CRD-2.F: Diseñar un programa y su interfaz de usuario. [Habilidad 1.B]
CRD-2.F.1 El diseño de un programa incluye la investigación para determinar sus requisitos.
CRD-2.F.2 La investigación en un proceso de desarrollo es útil para comprender e identificar las restricciones del programa, así como las preocupaciones e intereses de las personas que lo utilizarán.
CRD-2.F.3 Algunas formas en que se puede realizar la investigación son las siguientes:
recopilación de datos mediante encuestas
pruebas con usuarios
entrevistas
observaciones directas
CRD-2.F.4 Los requisitos de un programa describen cómo funciona y pueden incluir una descripción de las interacciones con el usuario que el programa debe proporcionar.
CRD-2.F.5 La especificación de un programa define los requisitos del mismo.
CRD-2.F.6 En un proceso de desarrollo, la fase de diseño describe cómo lograr la especificación dada del programa.
CRD-2.F.7 La fase de diseño de un programa puede incluir:
lluvia de ideas
planificación y guion gráfico
organización del programa en módulos y componentes funcionales
creación de diagramas que representen los diseños de la interfaz de usuario
desarrollo de una estrategia de pruebas para el programa
Objetivo de aprendizaje CRD-2.G: Describir el propósito de un segmento de código o de un programa escribiendo documentación. [Habilidad 4.A]
CRD-2.G.1 La documentación del programa es una descripción escrita de la función de un segmento de código, evento, procedimiento o programa y de cómo fue desarrollado.
CRD-2.G.2 Los comentarios son una forma de documentación del programa escrita dentro del mismo para ser leída por personas y no afectan el funcionamiento del programa.
CRD-2.G.3 Los programadores deben documentar un programa a lo largo de su desarrollo.
CRD-2.G.4 La documentación del programa ayuda a desarrollar y mantener programas correctos cuando se trabaja individualmente o en entornos de programación colaborativa.
CRD-2.G.5 No todos los entornos de programación admiten comentarios, por lo que pueden requerirse otros métodos de documentación.
Objetivo de aprendizaje CRD-2.H: Reconocer segmentos de código utilizados de otras fuentes. [Habilidad 1.C]
CRD-2.H.1 Es importante reconocer cualquier segmento de código que haya sido desarrollado de manera colaborativa o por otra fuente.
CRD-2.H.2 El reconocimiento de un segmento de código escrito por otra persona y utilizado en un programa puede realizarse en la documentación del programa. Dicho reconocimiento debe incluir el origen o el nombre del autor original.
Fuente: College Board AP Course and Exam Description
English
A programmer debugging at a multi-monitor workstation — iterative design and testing
Programs are built through an iterative 迭代的 process, not in one straight line: investigate the problem and users, design (often with a diagram 图示 or written plan), implement 实现 in code, and test – then repeat. A large problem is broken into smaller pieces (decomposition 分解). Comments 注释 and clear naming document the design so others (and your future self) can understand it. Development is incremental 增量的 – build and test a small piece, then add the next.
Common phases are investigating and reflecting, designing, building a prototype 原型 (an early working model), and testing. The order can be planned in advance or more exploratory, and a team may go back to an earlier phase at any time.
Worked example: iterative or incremental? The two words sound alike, and the exam separates them.
What the team does
Word
Why
Testers say the text is too small, so the team returns to the design and changes it
iterative
feedback sends them back to revise
The team makes questions display, tests that, then adds scoring, tests that, then adds a timer
incremental
one piece at a time, each working before it joins the whole
A real project usually does both.
The stages of program development, with testing feeding back to fix and refineSoftware is built by an iterative, incremental development process
Investigating what users actually need
Before any code is written, the developer investigates the problem and the people who will use the program. Ways to do that:
surveys 调查问卷 sent to potential users, which collect data from many people quickly;
interviews 访谈 and direct observation 观察 of users doing the task by hand;
user testing 用户测试, where people try an early version while the team watches;
studying existing solutions to see what already works and what frustrates people.
The findings are turned into a design. Two artefacts do that: a program requirements 程序需求 list saying exactly what the program must do, and diagrams representing the layout of the user interface 用户界面 — sketches showing which controls appear where, and what each one does when used. Designing the interface on paper first is cheaper than discovering after coding that the buttons are in the wrong place.
A program's specification 规格说明 defines its requirements. The design phase then plans how to meet them. It may include brainstorming, a storyboard 故事板 (a sequence of sketches of what the user sees), dividing the program into modules, and planning how it will be tested.
Events, and programs that wait
Not every program runs straight through from top to bottom. An event 事件 is generated when a key is pressed, a mouse is clicked, a program is started, or any other defined action occurs — and an event can change the flow of execution 执行流程 by triggering code attached to that event, called an event handler 事件处理程序. In many graphical programs, events wait in a queue until the current handler finishes.
This is why a program with a graphical interface can appear to be doing nothing: it is waiting for the next event. The order in which those events arrive depends on user actions and other event sources, so the same program can run its blocks in a different order each time it is used.
This style is called event-driven programming 事件驱动编程: statements run when they are triggered, not one after another from the top. The event also supplies input data, such as which key was pressed.
Documentation and credit
Program documentation 程序文档 is a written description of what a code segment, event, procedure or program does and how it was developed. Comments are one form: they are written for people and do not change how the program runs. Not every programming environment allows comments, so documentation sometimes lives in a separate file.
Write documentation throughout development, not at the end: it helps you and your teammates keep the program correct.
Code from someone else must be acknowledged: say in the documentation where it came from, with the original author's name if you know it. This applies to code written with a partner too.
Explorar
Recorrer el proceso de desarrollo iterativo
El desarrollo es iterativo: repites las etapas, mejorando el programa un poco en cada pasada. Recorre el ciclo y observa que vuelve al inicio en lugar de terminar después de una sola ejecución.
Comprensión perdurable (CRD-2): Los desarrolladores crean e innovan mediante un proceso de diseño iterativo centrado en el usuario, que integra ciclos de implementación y retroalimentación, y que deja amplio margen para la experimentación y la asunción de riesgos.
Objetivo de aprendizaje CRD-2.I: Para los errores en un algoritmo o programa:
a. Identificar el error. [Habilidad 4.C]
b. Corregir el error. [Habilidad 4.C]
CRD-2.I.1 Un error de lógica es un fallo en el algoritmo o programa que provoca que este se comporte de manera incorrecta o inesperada.
CRD-2.I.2 Un error de sintaxis es un fallo en el programa donde no se cumplen las reglas del lenguaje de programación.
CRD-2.I.3 Un error en tiempo de ejecución es un fallo en el programa que ocurre durante la ejecución de este. Los lenguajes de programación definen sus propios errores en tiempo de ejecución.
CRD-2.I.4 Un error de desbordamiento es un error que ocurre cuando una computadora intenta manejar un número que está fuera del rango de valores definido.
CRD-2.I.5 Las siguientes son formas efectivas de encontrar y corregir errores:
casos de prueba
trazado manual
visualizaciones
depuradores
añadir statement(s) de salida adicionales
Objetivo de aprendizaje CRD-2.J: Identificar entradas y salidas esperadas o comportamientos correspondientes que puedan utilizarse para verificar la corrección de un algoritmo o programa. [Habilidad 4.C]
CRD-2.J.1 En el proceso de desarrollo, las pruebas utilizan entradas definidas para asegurar que un algoritmo o programa produce los resultados esperados. Los programadores usan los resultados de las pruebas para revisar sus algoritmos o programas.
CRD-2.J.2 Las entradas definidas utilizadas para probar un programa deben demostrar los diferentes resultados esperados que están en o justo más allá de los extremos (mínimo y máximo) de los datos de entrada.
CRD-2.J.3 Se necesitan requisitos del programa para identificar las entradas definidas apropiadas para las pruebas.
Fuente: College Board AP Course and Exam Description
English
A bug is an error in a program; debugging 调试 is finding and fixing it. The exam names four kinds:
a syntax error 语法错误 breaks the language's rules, so the program will not run;
a runtime error 运行时错误 crashes the program while it runs (e.g. dividing by zero);
a logic error 逻辑错误 lets it run but gives the wrong result;
an overflow error 溢出错误 happens when a number is outside the range the computer can handle.
A trace table records each variable's value as the program runs, to find bugs
Find bugs by test cases 测试用例 with different inputs, adding print statements 打印语句 to see values, and hand-tracing 手动跟踪 the code. A debugger 调试器 stops the program at a chosen line so you can look at each variable, and a visualization 可视化 such as a chart can make a wrong pattern easy to see. Choose the test inputs deliberately: they should demonstrate the different expected outcomes at or just beyond the extremes — the minimum and maximum values the program should accept, and a value just outside each of them. A program that works on ordinary data very often fails on an empty list, a zero, or a value one past the end of a range, so those are the inputs worth trying first. Fixing one bug at a time and re-testing is the reliable method.
Worked example: choosing test inputs. A club sign-up page should accept ages 13 to 18. The requirements tell you the correct result, so you can choose inputs and say what you expect:
Test both ends of the range, and one step past each end
Five tests are enough: 12, 13, 15, 18 and 19. If the code says age > 13, only the test with 13 shows the fault; age 15 passes either way.
Exam skill: be able to name the type of an error and describe a testing strategy that would catch it – a recurring multiple-choice and Create-task theme.
Three common kinds of programming error: syntax, logic, and runtime
Worked example. A program meant to print the average of two numbers instead runs avg = a + b / 2. Tracing the order of operations 运算顺序, / runs before +, so it computes $a+\tfrac{b}{2}$ rather than the average. Add parentheses to fix it: avg = (a + b) / 2. Testing with $a=4,\ b=6$ confirms the fix — the buggy line gives $4+3=7$, the corrected line gives $\tfrac{10}{2}=5$. Testing with known inputs is exactly how you find and confirm a logic error.
Worked example: name the error.
What happens
Type
Reason
DISPLAY(score has no closing bracket; nothing runs
syntax
a language rule is broken
list[0] stops the program with an error message
run-time
AP lists start at index 1, and this only fails while running
A discount of 10% is taken as 10 dollars
logic
the program runs and the answer is wrong
A 4-bit counter at 1111 has 1 added
overflow
16 is outside the range
Written responses about your own program
Section II of the exam gives 60 minutes for two questions with four written prompts, all about the program you submitted for the Create task. You see your own code segments in your Personalized Project Reference, so answers must be about your program, not programs in general. Imagine this procedure is in yours:
PROCEDURE Average(numbers)
{
sum ← 0
FOR EACH n IN numbers
{
sum ← sum + n
}
RETURN(sum / LENGTH(numbers))
}
Past prompts have asked for the following.
A modification that causes a logic error, and how behavior changes. "If sum ← 0 is changed to sum ← 1, the procedure still runs, but every total is one too large. Average([2, 4]) returns $3.5$ instead of $3$."
A call the procedure accepts but handles wrongly. "Average([]): the empty list is accepted, but LENGTH(numbers) is 0, so the last line divides by zero and a run-time error stops the program." State the call, the wrong behavior and the reason: three separate things.
Documentation for another programmer. "A comment above the procedure saying that numbers must not be empty. Another programmer who reuses Average then knows to check for an empty list before calling it."
An unexpected input. Name one real input to your program and say what your program actually does next. If it rejects the input, say which line does that.
Common mistakes. Describing what a modification is without saying what changes when the program runs. Giving a call without specific argument values. Answering about a different procedure from the one the prompt names.
Explorar
Rastrear la lógica del juego de adivinanzas y detectar un error lógico
Arrastra el número de prueba y observa qué rama se ejecuta. Un error lógico enviaría el mismo número por la rama incorrecta: el programa sigue funcionando, pero muestra el mensaje equivocado. El número secreto aquí es 50.
A step-counter app counts steps and shows a daily total so users can meet a goal. State the program's purpose and one of its functions.
Classify each error as syntax, logic, run-time or overflow: (a) a missing closing bracket; (b) an average computed as sum / (count + 1); (c) dividing by a variable that is zero while the program runs; (d) adding $1$ to the largest value a fixed number of bits can store.
A procedure returns "pass" for scores of $60$ or more. Choose four test inputs and explain your choices.
Give one benefit of collaboration when designing a program.
Distinguish iterative development from incremental development.
Give two reasons for writing comments and other program documentation.
1.4
Respuestas
English
Purpose: help users meet a daily activity goal. Function: for example, it adds $1$ to the total each time a step is detected, or displays the total.
$59$, $60$ and $61$ test the boundary, where errors are most likely; an extreme such as $0$ or $100$ checks the limits of valid input.
Different perspectives help find errors and avoid bias, so the program works for more users (for example, pair programming catches mistakes earlier).
Iterative development repeats design, test and refine cycles, revising the program after feedback. Incremental development builds and tests the program in small pieces, adding one working part at a time.
It explains what code does and why, so others (and the author later) can understand, maintain and debug it; it also records sources of borrowed code.
1.4
Consejos de examen
English
Assessment includes multiple-choice questions and the Create component, with written responses on the AP exam. Explain your reasoning clearly, not just your result.
Know the benefits of collaboration and how diverse perspectives reduce bias in a program.
Use precise vocabulary (iterative, incremental, program requirements) when you describe a design process.
Test at and just beyond the extremes of the input range, and say the expected output for each test.
Give and take feedback 反馈 constructively; credit collaborators and sources.
Break a large problem into smaller modules that a team can build in parallel.