Hello,又来咯!让我们继续吧~
今天练习一下 for 循环和 if 语句经典练习,一起来看看吧~
1、使用for循环打印一个表格,要求用户输入表格的上下限,每一行打印一个整数、该数的平方、立方。
#include <stdio.h>
int main(void)
{
int n, MAX, MIN;
scanf("%d",&MAX); //用户输入表格上下限
scanf("%d",&MIN);
printf("n\tn_square\tn_cobe\n");
for (n = MIN; n <= MAX; n++)
printf("%-10d %-14d %-10d\n", n, n * n, n * n *n);
return 0;
}
字段宽度的控制还是有点麻烦的哟~
应该又更好的解决办法!
2、编写一个程序,把一个单词读入一个字符数组中,然后倒序打印这个单词。
#include<stdio.h>
int main(void)
{
int i,n;
char aph[n];
scanf("%s",&aph);
n = strlen(aph);
for(i = n; i <= n && i >= 0; i--)
{
printf("%c", aph[i]);
}
return 0;
}
3、在数组中读入8个整数,并将其倒序打印
method-1:
#include <stdio.h>
int main(void)
{
int i;
int n=8;
int aph[n];
for(i=0;i<n;i++)
scanf("%d",&aph[i]);
for(i = n-1; i >= 0; i--)
printf("%d\n", aph[i]);
return 0;
}
method-2:
#include<stdio.h>
int main()
{
int a[8],i,j,t;
for(i=0;i<8;i++)
scanf("%d",&a[i]);
for(j=7,i=0;j>=4;j--,i++)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
for(i=0;i<8;i++)
printf("%d ",a[i]);
return 0;
}
4、统计单词数量程序
#include <stdio.h>
#include <ctype.h> //为isspace()函数提供原型
#include <stdbool.h> //为bool、true、false提供定义
#define STOP '|'
int main(void)
{
char c; //读入字符
char prev; //读入的前一个字符
long n_chars = 0L; //字符数
int n_lines = 0; //行数
int n_words = 0; //单词数
int p_lines = 0; //不完整的行数
bool inword = false;
printf("Enter text to be analyzed (| to terminate):\n");
prev = '\n'; //用于识别完整的行
while((c = getchar()) != STOP)
{
n_chars++; //统计字符数
if (c == '\n')
n_lines++; //统计行数
if (!isspace(c) && !inword)
{
inword = true; //开始一个新的单词
n_words++; //统计单词数
}
if(isspace(c) && inword)
inword = false; //单词末尾
prev = c; //保存字符的值
}
if(prev != '\n')
p_lines = 1;
printf("characters = %ld, words = %d, lines = %d, ",
n_chars, n_words, n_lines);
printf("partial lines = %d\n",p_lines);
return 0;
}
好哒~加油!