码迷,mamicode.com
首页 > 编程语言 > 详细

C语言:一些做过的算法题。

时间:2014-09-17 07:49:21      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

1. 练习:输入一个数,得到数的长度(位数)。

#include <stdio.h>
int main()
{
    int a;
    int count=0;
    printf("请输入一个数:");
    scanf("%d", &a);
    for (;;) {
        a/=10;
        if (a!=0) {
            count++;
        } else break;
    }

    printf("%d\n", count);
}

2. 将a中n个整数按相反方向存放。(这类算法需要线下手动设计)。

#include <stdio.h>
void inv(int *x, int y)
{
    int temp,i,j;
    int m=(y-1)/2; //取数组中间的部分
    for (i=0;i<=m;i++) {
        j=y-1-i; //获取i相对应的最右边的下标
        temp=x[i];
        x[i]=x[j];
        x[j]=temp;
    }
    return;
}

int main()
{
    //把数组a中n个整数按倒序排列。
    int a[] = {1,23,33,44,55,66};
    inv(a,6);
    for (int i=0;i<6;i++) printf("%d, ", a[i]);
    printf("\n");
}

3. 用选择法对10个整数按由大到小顺序排列。

4.将字符串a复制为字符串b。最关键的地方是for循环中第二个起判断的第二个表达式用 *(a+i)!=‘\0‘

#include <stdio.h>
int main()
{
    char a[] = "I am a boy", b[20];
    for (int i=0;*(a+i)!=\0;i++) {
        b[i]=*(a+i);
     }
     for (int i=0;*(b+i)!=0;i++) {
         printf("%c", b[i]);
     }
}

第二种方法:

while ((*b=*a)!=\0) {
    a++;
    b++;
}

 第三种方法:

while ((*b=*a++)!=\0);

第四中方法:

while(*a!=\0) {
    *b++=*a++;
    *b=\0
}

 

C语言:一些做过的算法题。

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/zuiaishenlin/p/3975015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!