[英]'Try This' exercise on Programming Principles and Practice Using C++, For iteration
I'm studying in this book (self study) and I'd really appreciate if you could help me with a little 'try this' exercise. 我正在读这本书(自学),如果你能帮助我做一点'尝试'这个练习,我真的很感激。
This is the code I wrote: 这是我写的代码:
#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;
}
The next step, according to the book, is: "[...] then modify your program to also write out a table of the integer values for uppercase letters and digits" Is there a function to do that, or do I simply have to repeat the loop starting from A? 根据这本书,下一步是:“[...]然后修改你的程序,也写出一个大写字母和数字的整数值表”是否有一个功能,或者我只是有重复从A开始的循环? Thanks
谢谢
Yes, repeat the loop from 'A' to 'Z' and '0' to '9'. 是的,重复从'A'到'Z'和'0'到'9'的循环。
Assuming your book has covered functions (which it may not have), you might refactor your for loop into its own function perhaps called displayCharactersInTable which takes as arguments the first character and last character. 假设你的书已经涵盖了函数(它可能没有),你可以将你的for循环重构为它自己的函数,也许叫做displayCharactersInTable,它将第一个字符和最后一个字符作为参数。 Those would replace the use of 'a' and 'z' in the loop.
那些将取代循环中'a'和'z'的使用。 Thus your main function would look like:
因此,您的主要功能如下:
...
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;
}
This code does not assume that character representations are contiguous (or even increasing alphabetically), so it will work for all character encodings. 此代码不假定字符表示是连续的(甚至按字母顺序增加),因此它适用于所有字符编码。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.