6-x 第六章总结与测验

快速回顾

若存在疑问或混淆可能,请始终使用括号明确运算符的优先级。

算术运算符均遵循常规数学规则。取模运算符(%)返回整数除法的余数。

递增与递减运算符可便捷地增减数值。尽可能避免使用后缀形式的运算符。

需警惕副作用,尤其注意函数参数的求值顺序。避免在单个语句中多次使用已产生副作用的变量。

逗号运算符可将多个语句压缩为一条,但通常建议分开编写语句。

条件运算符conditional operator( ?: )(有时称为算术条件arithmetic if运算符)是三元运算符(接受三个操作数的运算符)。对于 c ? x : y 形式的条件操作,若条件 c 求值为真则执行 x,否则执行 y。条件运算符通常需按以下方式加括号:

  • 在复合表达式(含其他运算符的表达式)中使用时,需将整个条件运算符括起来。
  • 为提高可读性,若条件表达式包含任何运算符(函数调用运算符除外),应将其括起来。

关系运算符可用于比较浮点数。注意浮点数使用等号和不等号时需谨慎。

逻辑运算符允许我们构建复合条件语句。


测验时间

完成以下程序:

#include <iostream>

// Write the function getQuantityPhrase() here

// Write the function getApplesPluralized() here

int main()
{
    constexpr int maryApples { 3 };
    std::cout << "Mary has " << getQuantityPhrase(maryApples) << ' ' << getApplesPluralized(maryApples) << ".\n";

    std::cout << "How many apples do you have? ";
    int numApples{};
    std::cin >> numApples;

    std::cout << "You have " << getQuantityPhrase(numApples) << ' ' << getApplesPluralized(numApples) << ".\n";

    return 0;
}

示例输出:

Mary has a few apples.
How many apples do you have? 1
You have a single apple.

getQuantityPhrase() 函数应接受一个整型参数,该参数表示某物的数量,并返回以下描述符:

  • < 0 = “negative”
  • 0 = “no”
  • 1 = “a single”
  • 2 = “a couple of”
  • 3 = “a few”
  • > 3 = “many”

getApplesPluralized() 函数应接受一个整型参数表示苹果数量,并返回以下结果:

  • 1 = “apple”
  • otherwise = “apples”

该函数应使用条件运算符。

image

显示提示

提示:函数返回C风格字符串常量时,将其作为std::string_view返回是可行的。

显示解决方案

#include <iostream>
#include <string_view>

std::string_view getQuantityPhrase(int num)
{
    if (num < 0)
        return "negative";
    if (num == 0)
        return "no";
    if (num == 1)
        return "a single";
    if (num == 2)
        return "a couple of";
    if (num == 3)
        return "a few";
    return "many";
}

std::string_view getApplesPluralized(int num)
{
    return (num == 1) ? "apple" : "apples";
}

int main()
{
    constexpr int maryApples { 3 };
    std::cout << "Mary has " << getQuantityPhrase(maryApples) << ' ' << getApplesPluralized(maryApples) << ".\n";

    std::cout << "How many apples do you have? ";
    int numApples{};
    std::cin >> numApples;

    std::cout << "You have " << getQuantityPhrase(numApples) << ' ' << getApplesPluralized(numApples) << ".\n";

    return 0;
}
posted @ 2026-02-19 18:51  游翔  阅读(1)  评论(0)    收藏  举报