Hours

Learning Goals

  • Practice using arrays
  • Using an array as a parameter to a function
  • Adding values in a loop
  • Integer division and type casting

OfficeHours

背景

Suppose you’re taking CS50 (if you’re reading this you probably are!) and spending时间 every周on each 问题集. You可能是 wondering how many hours you’ve spent learning 计算机科学, on average or in total! In this program, you’ll complete a function that calculates, based on a user’s input, a total number of hours or an average number of hours across a given number of days.

  • 提示
    • To add up numbers in an array, you might first want to initialize a variable to zero. After, you’ll want to use a loop that adds each value in the array to that variable.
    • 请务必 pay attention to what happens if you divide two ints when calculating the average!

演示

HoursGif

入门

  1. Log into cs50.dev using your GitHub account.
  2. Click inside the terminal window and execute cd.
  3. At the $ prompt, type mkdir hours
  4. Now execute cd hours
  5. Then copy and paste wget https://cdn.cs50.net/2022/fall/实验s/2/hours.c into your terminal to 下载 this 实验’s 分发代码.

实现细节

The main function prompts the user 的 number of周a user has been taking CS50, then creates an array with as many elements. 注意, after retrieving some data, the program prompts the user to type in either “T” or “A”—”T” should (but doesn’t yet!) print the total number of hours the user entered, while “A” should (but doesn’t yet!) print the average hours the user entered. 注意 the do while loop uses toupper to capitalize the letter that’s input before it is saved in the variable output. Then, the printf function calls calc_hours. 笔记 the syntax involved when passing an array to a function.

To complete calc_hours, first total up the hours saved in the array into a new variable. Then, depending on the value of output, return either this sum, or the average number of hours.

Thought 问题

  • What is the advantage of using a function to calculate hours?

如何测试 Your Code

你的程序应该 behave per the例子below.

hours/ $ ./hours
Number of weeks taking CS50: 3
第 0 周 HW Hours: 3
第 1 周 HW Hours: 7
第 2 周 HW Hours: 10
Enter T for total hours, 一份 for average hours per week: A
6.7 hours
hours/ $ ./hours
Number of weeks taking CS50: 2
第 0 周 HW Hours: 2
第 1 周 HW Hours: 8
Enter T for total hours, 一份 for average hours per week: T
10.0 hours

You can check your code using check50, a program that CS50 will use to test your code when you 提交, by typing in the following at the $ prompt. But be sure to test it自己 as well!

check50 cs50/实验s/2023/x/hours

To evaluate that the style of your code, type in the following at the $ prompt.

style50 hours.c

如何提交

No need to 提交! This is an 可选 练习题 completed with your 实验.