Getting started with the basics of programming exercises_2
2015-04-27 18:31 星星之火✨🔥 阅读(137) 评论(0) 收藏 举报1、编写简单power函数
#include<stdio.h> int power(int m, int n); // test power function int main(void) { int i; for(i = 0; i < 10; ++i) { printf("%d %d %d\n", i, power(2, i), power(-3, i)); } return 0; } // power: raise base to n-th power; n >= 0 int power(int base, int n) { int i, p; p = 1; for(i = 1; i <= n; ++i) p = p * base; return p; }
其中power函数如果直接使用形参n的话,可以使程序更简洁
int power(int base, int n) { int p; for(p = 1; n > 0; --n) p = p * base; return p; }
2、读入一组文本行,并把最长的文本行打印出来
简单写下算法框架: while(还有未处理的行) if(改行比已处理的最长行还要长) 保存改行为最长行 保存改行的长度 打印最长的行 |
程序如下:
#include<stdio.h> #define MAXLINE 1000 // maxinmum input line length int getline(char line[], int maxline); void copy(char to[], char from[]); // print the longest input line int main(void) { int len; // current line length int max; // maximum length seen so far char line[MAXLINE]; // current input file char longest[MAXLINE]; // longest line saved here max = 0; while((len = getline(line, MAXLINE)) > 0) { if(len > max) { max =len; copy(longest, line); } } if(max > 0) // there was a line printf("%s", longest); return 0; } /* getline: read a line into s, return length 读入文本行时返回改行的长度, 而在遇到文件结束符时返回0. 由于0不是有效的行长度,因此可以作为标志文件结束的返回值。 每一行至少包括一个字符,只包含换行符的行,其长度为1. */ int getline(char s[], int lim) { int c, i; for(i = 0; i < lim -1 && (c = getchar()) != EOF && c != '\n'; ++i) // 检查是否溢出,因为程序无法预知输入行长度 s[i] = c; if(c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } // copy: copy 'from' into 'to': assume to is big enough void copy(char to[], char from[]) { int i; i = 0; while((to[i] = from[i]) != '\0') ++i; }
3、打印任意长度的输入行的长度,并尽可能多地打印文本
#include<stdio.h>
#define MAXLINE 1000 // maximum input line size
int getline(char line[], int maxline);
void copy(char to[], char from[]);
// print longest input line
int main(void)
{
int len; // current line length
int max; // maximum length seen so far
char line[MAXLINE]; // current input line
char longest[MAXLINE]; // longest line saved here
max = 0;
while((len = getline(line, MAXLINE)) > 0)
{
printf("%d %s", len, line);
if(len > max)
{
max = len;
copy(longest, line);
}
}
if(max > 0) // there was a line
printf("%s", longest);
return 0;
}
// copy: copy 'from' into 'to'; assume to is big enough
void copy(char to[], char from[])
{
int i;
i = 0;
while((to[i] = from[i]) != '\0')
++i;
}
// getline: read a line into s, return length
int getline(char s[], int lim)
{
int c, i, j; // i记录字符串长度, j记录被复制到字符串s中的字符的个数
j = 0;
for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
if(i < lim-2)
{
s[j] = c; // line still in boundaries
++j;
}
if(c == '\n')
{
s[j] = c;
++j;
++i;
}
s[j] = '\0';
return i;
}