原题:http://acm.timus.ru/problem.aspx?space=1&num=1823
题意:pV = nRT (克拉珀龙方程) R为已知量(= 8.314) 输入其中三个变量的值,求另一个变量。
思路:因为题中限定V、T大于零,所以我们可以对p、n是否为零进行讨论。
undefined是答案不确定;error则为两种情况:1. 与V、T大于零矛盾;2.除数为零;
#include<stdio.h>
#include<string.h>
const double R = 8.314;
int s[10];
int x;
int num;
char s1[10], s2[10];
int pre(char a[10]) //将字母转化为数字来讨论,更为方便
{
if(a[0] == 'p') return 1;
else if(a[0] == 'V') return 2;
else if(a[0] == 'n') return 3;
else if(a[0] == 'T') return 4;
return 0;
}
int res() //s[x] == -1则表示所求变量为x
{
if(s[1] == 0&&s[3] == 0)
printf("undefined\n");
else if(s[1] == 0&&s[3] != 0)
{
if(s[2] == -1)
printf("error\n");
else if(s[3] == -1)
printf("n = 0\n");
else if(s[4] == -1)
printf("error\n");
}
else if(s[1] != 0&&s[3] == 0)
{
if(s[1] == -1)
printf("p = 0\n");
else if(s[2] == -1)
printf("error\n");
else if(s[4] == -1)
printf("error\n");
}
else if(s[1] !=0 && s[3] != 0)
{
if(s[1] == -1)
{
double ans = (double)(s[3]*R*s[4])/s[2];
printf("p = %.6f\n", ans);
}
else if(s[2] == -1)
{
double ans = (double)(s[3]*R*s[4])/s[1];
printf("V = %.6f\n", ans);
}
else if(s[3] == -1)
{
double ans = (double)(s[1]*s[2])/(R*s[4]);
printf("n = %.6f\n", ans);
}
else if(s[4] == -1)
{
double ans = (double)(s[1]*s[2])/(R*s[3]);
printf("T = %.6f\n", ans);
}
}
return 0;
}
int main()
{
while(scanf("%s%s%d", s1, s2, &num)!=EOF)
{
memset(s, -1, sizeof(s));
x = pre(s1);
s[x] = num;
scanf("%s%s%d", s1, s2, &num);
x = pre(s1);
s[x] = num;
scanf("%s%s%d", s1, s2, &num);
x = pre(s1);
s[x] = num;
res();
}
return 0;
}