《C语言入门经典》习题7.1(仅供与某人讨论使用)

来源:互联网 发布:java开发百度云播放器 编辑:程序博客网 时间:2024/05/18 05:42

#include <stdio.h>#include <stdlib.h>#include <math.h>int main(void){char ch;int a = 5;long count = 0L,number = 0L;char *p = NULL, *b = NULL;long double sum = 0.0L, result = 0.0L;printf("使用说明:""\n本程序可对输入的数值进行相加操作。""\n按回车键结束输入。\n""(注意:每次仅限一个数值。)\n\n");p = calloc(a, sizeof(char));if (p == NULL){printf("\a警告:内存分配失败!\n");return 1;}while (*p != '\n'){number++;printf("请输入第%d个数值:", number);count = 0L;while (*p != '\n'){++count;ch = getchar();if (ch == '\n'){if (count >= a){a += 5;b = realloc(p, a*sizeof(char));if (b == NULL){printf("\a警告:内存分配失败!\n");free(p);p = NULL;return 1;}p = b;}*(p + count - 1) = ch;*(p + count) = '\0';break;}else{if (count >= a){a += 5;b = realloc(p, a*sizeof(char));if (b == NULL){printf("\a警告:内存分配失败!\n");free(p);p = NULL;return 1;}p = b;}*(p + count - 1) = ch;*(p + count) = '\0';}}sum = (long double)atof(p);result += sum;}printf("%lf\n", result);free(p);p = NULL;system("pause");return 0;}

原创粉丝点击