C语言实例:键盘输入一个算术的运算式子,输出运算结果
键盘输入一个算术的运算式子,输出运算结果。这里我们规定可以接收五个算术运算的符号:+、-、*、/、^(乘方)
输入一个加法的算术式:
程序代码:
#include<stdio.h>
#include<math.h>
int main(void)
{
/*init 0.0*/
double a = 0.0;
double b = 0.0;
char op = '0'; /* + - * / ^*/
printf("Enter a expression:");
/*must be %lf beacuse we use double*/
scanf("%lf%c%lf",&a,&op,&b);
switch(op)
{
case '+':
printf("%.2f + %.2f = %.3f",a,b,(a+b));
break;
case '-':
printf("%.2f - %.2f = %.3f",a,b,(a-b));
break;
case '*':
printf("%.2f * %.2f = %.3f",a,b,(a*b));
break;
case '/':
if (fabs(b-0.0) < 0.0000001)
{
printf("Input Err.\n");
break;
}
printf("%.2f * %.2f = %.3f",a,b,(a/b));
break;
case '^':
printf("%.2f ^ %.2f = %.3f",a,b,pow(a,b));
break;
default:
printf("Input Err.\n");
}
return 0;
}
某服装店经营套服。以50套为限,若购买数量不少于50套,每套80元;不足50套时每套90元;只买上衣每件60元;只买裤子每条45元。编写程序实现:读入所买上衣c和裤子t的数量,计算应付款总量。
程序代码:
#include<stdio.h>
int main(void)
{
int clths = 0;
int trs = 0;
int suit = 0;
int money = 0;
printf("Clothes:");
scanf("%d",&clths);
printf("Trousers:");
scanf("%d",&trs);
if (clths > trs)
{
suit = trs;
if (suit >= 50)
{
money = suit * 80;
}
else
{
money = suit * 90;
}
money += (clths-trs)*60;
}
else
{
suit = clths;
if (suit >= 50)
{
money = suit * 80;
}
else
{
money = suit * 90;
}
money += (trs-clths)*45;
}
printf("Money:%d",money);
return 0;
}
按yyyy-mm-dd格式输入一个日期,如2004-10-31,判断这是这一年的第几天。
程序代码:
#include<stdio.h>
int main(void)
{
int year = 0;
int month = 0;
int day = 0;
int past = 0;
printf("Please Input a day(Eg.yyyy-mm-dd):");
scanf("%d-%d-%d",&year,&month,&day);
past += day; /* 2011-3-6 = 6+28+31 =65 */
/* 31 28 or 29 31 30 31 30 31 31 30 31 30 31 */
/* no break; */
switch(month-1)
{
case 12:
past += 31;
case 11:
past += 30;
case 10:
past += 31;
case 9:
past += 30;
case 8:
past += 31;
case 7:
past += 31;
case 6:
past += 30;
case 5:
past += 31;
case 4:
past += 30;
case 3:
past += 31;
case 2:
if (((year%4==0)&&(year%100!=0))||(year%400==0))
{
past +=29;
/* printf("leap\n"); */
}
else
{
past +=28;
}
case 1:
past +=31;
case 0:
break;
default:
printf("Input may be wrong.");
break;
}
printf("Today is %dth of %d:",past,year);
return 0;
}