加载中...

CS50 Practice Problems


Week1-Practice Problems

Practice Problems Page: https://cs50.harvard.edu/x/2023/problems/1/

CS50 Study Group:677535709(QQ Group)

These problems assume that you have already set up your CS50 Codespace in Lab 1. Be sure to complete that before attempting these problems.

In addition to this week’s lab and problem set, you’re welcome to try any of these (optional!) practice problems:

  • Debug, for becoming familiar with C syntax and debugging programs
  • Half, for practice creating a function
  • Prime, for practice using for loops

P1-Debug

https://cs50.harvard.edu/x/2023/problems/1/debug/

Learning Goals 🎯

  • Become familiar with C syntax
  • Learn what C compiler error messages mean
  • Get practice debugging

Code 🧑🏻‍💻

// Become familiar wih C syntax
// Learn to debug buggy code

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    // Ask for your name and where live
    string name = get_string("What is your name? ");
    string location = get_string("Where do you live? ");

    // Say hello
    printf("Hello, %s, from %s!\n", name, location);
}

P2-Half

Learning Goals 🎯

  • Work with different data types
  • Practice type casting
  • Use math operations
  • Create a function with input parameters and return value

Code 🧑🏻‍💻

// Calculate your half of a restaurant bill
// Data types, operations, type casting, return value

#include <cs50.h>
#include <stdio.h>

float half(float bill, float tax, int tip);

int main(void)
{
    float bill_amount = get_float("Bill before tax and tip: ");
    float tax_percent = get_float("Sale Tax Percent: ");
    int tip_percent = get_int("Tip percent: ");

    printf("You will owe $%.2f each!\n", half(bill_amount, tax_percent, tip_percent));
}

// TODO: Complete the function
float half(float bill, float tax, int tip)
{
    // add tax to the bill
    bill += bill * tax / 100.0;

    // add tip to the bill
    bill += bill * tip / 100.0;

    // split the bill
    return bill / 2.0;
}

P3-Prime

https://cs50.harvard.edu/x/2023/problems/1/prime/

Learning Goals 🎯

  • Practice using for loops
  • Using modulo
  • Creating a Boolean function

Code 🧑🏻‍💻

#include <cs50.h>
#include <stdio.h>

bool prime(int number);

int main(void)
{
    // get the lower bound
    int min;
    do
    {
        min = get_int("Minimum: ");
    }
    while (min < 1);

    // get the upper bound
    int max;
    do
    {
        max = get_int("Maximum: ");
    }
    while (min >= max);

    // list prime numbers in this range
    for (int i = min; i <= max; i++)
    {
        if (prime(i))
        {
            printf("%i\n", i);
        }
    }
}

// check if number is a prime number
bool prime(int number)
{
    // TODO
    for (int i = 2; i <= number / i; i++)
    {
        if (number % i == 0)
        {
            return false;
        }
    }
    return true;
}

文章作者: Rickyの水果摊
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Rickyの水果摊 !
  目录