欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

《C语言入门经典》习题7.1【原创】

程序员文章站 2022-08-04 18:15:01
《c语言入门经典》习题7.1【原创】 #include #include #include int main(void) { char ch; int a = 5;...

《c语言入门经典》习题7.1【原创】

#include 
#include 
#include 

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;
}