编程入门:变量、运算与操作实践
1. 变量声明与使用
在编程中,变量的正确声明和使用至关重要。若尝试编译以下代码:
// Display some output
printf("%d brides for %d brothers\n", Brides, brothers);
return 0;
}
会得到错误信息。编译器会将 brides
和 Brides
视为不同的名称,由于未声明 Brides
,编译器无法理解其指代内容。这是常见错误,标点和拼写错误是小错误的主要成因。使用变量前必须先声明,否则编译器无法识别,会将语句标记为错误。
以下是一个简单计算程序示例:
// Program 2.4 Simple calculations
#include <stdio.h>
int main(void)
{
int total_pets;
int cats;
int dogs;
int ponies;
int others;
// Set the number of each kind of pet
cats = 2;
dogs = 1;
ponies = 1;
others = 46;
// Calculate the total number of pets
total_pets = cats + dogs + ponies + others;
printf("We h