各位达人,在Pointer on C中的习题里,有这样一个题:
Write a program that reads characters from the standard input and writes them to the standard output. It should also compute a checksum and write it out after the characters.
The checksum is computed in a signed char variable that is initialized to —1. As each character is read from the standard input, it is added to the checksum. Any overflow from the checksum variable is ignored. When all of the characters have been written, the checksum is then written as a decimal integer, which may be negative. Be sure to follow the checksum with a new‐line. On computers that use ASCII, running your program on a file containing the words ʺHello world!ʺ followed by a newline should produce the following output:
Hello world!
102
我不明白其中checksum是什么概念,然后看了答案代码。如下:
/* checksum.c */
/*
** This program copies its standard input to the standard output, and computes ** a checkusm of the characters. The checksum is printed after the input.
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c;
char sum = -1;
/*
** Read the characters one by one, and add them to the sum.
*/
while((c = getchar()) != EOF){
putchar(c);
sum += c;
}
printf("%d\n", sum);
return EXIT_SUCCESS;
}
运行结果:
其中一次运行:
What does "checksum" mean anyway?
What does "checksum" mean anyway?
^Z
-40
另一次运行:
Gottya!
Gottya!
^Z
-94
编译运行后,那个checksum的值有时是个正数有时是个负数。不过不知为何会这样,这跟signed char的性质有关系吗?另外,这里的checksum是个什么概念?请达人帮忙解释一下,谢谢!