codeforces A. IQ Test 解题报告

题目链接:http://codeforces.com/problemset/problem/328/A

一开始单纯地直接判断给出的序列是等差还是等比,连这一句“You should also print 42 if the next element of progression is not integer ”  都直接忽略,因为 Output 中没说,只是描述里讲了(要积累经验啊!!),其实是大错特错!

这个题目的关键是,当判断出给定的序列是等比时,求出下一个数(假设为result)是否是小数的判断(等差就没有这个问题,因为都是整数)。这里我采取的办法是把浮点型的result(用来保存待求的下一个数)转化为字符型s(字符型能够方便地看到是否存了小数点),然后通过strchr找到小数点的位置,判断小数点后的第一个数和字符型最后一个数是否是0,如果都为0,说明不是小数(类似这种表示:10000.000000,因为转化为字符型的s时是以 %lf 的格式来转的,默认情况下它会保留到小数点后6位),否则为小数。

 #include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std; int main()
{
int a, b, c, d, flag;
double a1, b1, c1;
char *p, s[];
while (cin >> a >> b >> c >> d)
{
flag = ;
if (b - a == c - b && c - b == d - c)
{
printf("%d\n", (d-c)+d);
flag = ;
}
a1 = (double)b * 1.0 / a; // 强制类型转换,把整型转化为双精度,考虑到公比有可能是小数
b1 = (double)c * 1.0 / b;
c1 = (double)d * 1.0 / c;
// cout << a1 << " " << b1 << " " << c1 << endl;
if (a1 == b1 && b1 == c1 && !flag)
{
double result = a1 * d;  // 保存要求的下一个数
sprintf(s, "%lf", result);
// cout << "s = " << s << endl;
p = strchr(s, '.');  // 特别要注意得出的p不是小数点的位置
int pos = p - s; // 找到小数点的位置
// cout << "pos+1 = " << pos+1 << endl;
// cout << "s[strlen(s)] = " << s[strlen(s)-1] << endl;
if (s[pos+] == '' && s[strlen(s)-] == '')  // 这两个条件可以判断出求出的下一个数是否是小数
{
printf("%.0lf\n", result);  // 不是小数,而是整数(类似123.000这种表示)
}
else  // 等比序列中求出的下一个数是小数
{
printf("42\n");
}
flag = ;
}
if (!flag)  // 既不是等差又不是等比
printf("42\n");
}
return ;
}
上一篇:vue路由懒加载及组件懒加载


下一篇:Activiti流程图查看