找零錢程序
要求輸入金額,輸出找零金額。
int main()
{
int amount=100;
int price=0;
printf("請輸入需付金額(元):");
scanf("%d",&price);
printf("請輸入支付金額:");
scanf("%d",&amount);
int change=amount-price;
printf("找您%d元。\n",change);
return 0;
}
運行結果
超級簡單的加法
輸入兩個整數,計算它們的和。
int main()
{
int a=0;//要記得初始化
int b=0;
printf("請輸入兩個整數:");
scanf("%d %d",&a,&b);
printf("%d + %d = %d\n",a,b,a+b);
return 0;
}
運行結果
計算身高的程序
int main()
{
printf("請分別輸入身高的英尺和英寸,"
"如輸入\"5 7\"表示5英尺7英寸:");
int foot;
int inch;
scanf("%d %d",&foot,&inch);
printf("身高是%f米。\n",((foot+inch/12)*0.3048));
return 0;
}
運行結果1
運行結果2
!!!出現錯誤
●兩個整數的運算的結果只能是整數
●10/3*3=>?
●10和10.0在C中 是完全不同的數
●10.0是浮點數
改進代碼
int main()
{
printf("請分別輸入身高的英尺和英寸,"
"如輸入\"5 7\"表示5英尺7英寸:");
int foot;
int inch;
scanf("%d %d",&foot,&inch);
printf("身高是%f米。\n",((foot+inch/12.0)*0.3048));
return 0;
}
第二種改進方法
int main()
{
printf("請分別輸入身高的英尺和英寸,"
"如輸入\"5 7\"表示5英尺7英寸:");
double foot;
double inch;
scanf("%lf %lf",&foot,&inch);
printf("身高是%f米。\n",((foot+inch/12)*0.3048));
return 0;
}
數據類型
整數
- int
- printf("%d",… )
- scanf("%d",…)
帶小數點的數
- double
- printf("%f,…)
- scanf("%lf,…)