C语言整数求和

带注释

#include    //头文件
int main(void)   //主函数无参数,返回的值是整数
{
	long num;   //定义了一个长整型变量num
	long sum=0L;   //定义了一个长整型变量sum,把sum初始化为long类型的0
	printf("Please input an integer to sum up. End with the letter f\nYou can input and press Enter:");   //提示用户输入整数来求和,以f结束(其实输入任何非数值的数也可以做到)
	while(1==scanf("%d",&num))   //若scanf()读取到了整数就将其存入num中并返回1,再判断是否与1相等,相等,循环;若scanf()读取不成功(用户输入的非数字)就返回0,再判断是否与1相等,不相等,循环结束
	{
		sum+=num;   //sum=sum+num,求和
		printf("You can input and press Enter:");   //可以继续输入
	}
	printf("\nSo let's calculate the sum:%ld\n",sum);   //求和结果以长整型格式输出
	return 0;   //返回语句
}

不带注释

#include 
int main(void)
{
	long num;
	long sum=0L;
	printf("Please input an integer to sum up. End with the letter f\nYou can input and press Enter:");
	while(1==scanf("%d",&num))
	{
		sum+=num; 
		printf("You can input and press Enter:");
	}
	printf("\nSo let's calculate the sum:%ld\n",sum);
	return 0;
}

运行

C语言整数求和_第1张图片

你可能感兴趣的:(c语言)