示例代码
#include <stdio.h>
int main(void)
{
int total_pets;
int cats;
int dogs;
int ponies;
int others;
//给每一个宠物变量设置值
cats = 2;
dogs = 1;
ponies = 1;
others = 46;
//计算总的宠物数
total_pets = cats + dogs + ponies + others;
printf("我们总共有%d只宠物。\n",total_pets); // 输出结果
return 0;
}Code language: PHP (php)
程序运行输出结果(对应控制台窗口):
我们总共有50只宠物。
Process exited after 0.1075 seconds with return value 0
请按任意键继续...Code language: JavaScript (javascript)
代码说明
这里定义了五个变量,其中一个(total_pets)用来存储总数。
其它四个变量(cats、dogs、ponies、others)分别赋予不同的值(2、1、1、46)。
核心计算语句:
total_pets = cats + dogs + ponies + others;
将前四个变量的值进行相加,把得到的结果(50)赋值给 total_pets 变量。
最后通过 printf("我们总共有%d只宠物。\n",total_pets); 将总数打印输出。与前面的例子一样,使用 %d 作为转换说明符,将 total_pets 中的整数值替换并输出到屏幕上。