关于编程原理和C++练习的"尝试这个"练习,用于迭代

'Try This' exercise on Programming Principles and Practice Using C++, For iteration

本文关键字:练习 迭代 用于 C++ 于编程 编程      更新时间:2023-10-16

我正在学习这本书(自学),如果你能帮我做一点"试试这个"练习,我将不胜感激。

这是我写的代码:

#include "../../../std_lib_facilities.h"
int main()
{
    for (char i ='a'; i <='z'; ++i) {
        int x = i;
        cout << i << 't' << x << 'n';
    }
    keep_window_open();
    return 0;
}

根据这本书,下一步是:"[…]然后修改程序,为大写字母和数字写出一个整数值表。"有没有函数可以做到这一点,或者我只需要重复从a开始的循环?感谢

是,重复从"A"到"Z"和从"0"到"9"的循环。

假设你的书中包含了一些函数(可能没有),你可以将for循环重构为它自己的函数,可能称为displayCharactersInTable,它将第一个字符和最后一个字符作为参数。这些将取代在循环中使用"a"answers"z"。因此,您的主要功能看起来像:

...
displayCharactersInTable('a', 'z');
displayCharactersInTable('A', 'Z');
displayCharactersInTable('0', '9');
...
const char lc_alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const char uc_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main() {
    for (const char *cur = lc_alphabet; cur < lc_alphabet + sizeof(lc_alphabet); ++cur)
        std::cout << *cur << t << (int)*cur << 'n';
    for (const char *cur = uc_alphabet; cur < uc_alphabet + sizeof(uc_alphabet); ++cur)
        std::cout << *cur << t << (int)*cur << 'n';
return 0;
}

此代码不假设字符表示是连续的(甚至按字母顺序递增),因此它适用于所有字符编码。

int b = 97; // the corresponding decimal ascii code for 'a'
int a = 65; // the corresponding decimal ascii code for 'A'
for(int i = 0; i < 26; ++i)
    cout << char('A' + i) << 't' << a << 't' << char('a' + i) << 't' << b << 'n'; //print out 'A' and add i, print out a, print out 'a' and add i, print out b
    ++a; //increment a by 1
    ++b; //increment b by 1