曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 4719|回复: 0
打印 上一主题 下一主题

百度知道中的题目一

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2008-11-16 22:42:15 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
如输入一个数字串:100 200 400 100 500

然后反向输出: 500 100 400 200 100

最后求头两个和尾两个数的平均值。

我的解法:(编译环境为linux gcc,gcc 编译带有数学函数库时,需加参数 -lm )

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define MAXSIZE 100
#define NUM     10

char string[MAXSIZE];
int len;
int main()
{
    char *ptr;
    int temp = 0;
    int i = 0;
    int k = 0;
    int num[NUM];
    printf("Please enter: ");

    if( fgets(string, MAXSIZE, stdin) == NULL ){
        printf("Read error.\n");
        exit(1);
          }
   
         len = strlen(string);
             
     ptr = &string[len-2];

    len = len-2;
   
    while( len >= 0 )
  {

     while( *ptr != ' ' && len >= 0)
    {
        if( i == 0 ){
            temp = *ptr-48;
            i = 1;
            ptr--;
            len--;
            continue;
        }else  {
            temp += (*ptr-48) * (int)pow(10,i);       
            ptr--;
            i++;
            len--;
            continue;
        }

    }
        ptr--;
        i = 0;                //reset i for next number
        num[k] = temp;
        k++;
        printf("%d ", temp);
        temp = 0;
        len--;
   }   
       
  printf("\n");

  printf("avg_1 = %d\n",(num[0] + num[1])/2 );

  printf("avg_2 = %d\n",(num[k-1] + num[k-2])/2 );

  return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-6-18 17:17 , Processed in 0.062523 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表