7-11问题

一位顾客在7-11买了4件商品,这4件商品相乘的价格是7.11元,相加的价格也是7.11元,请用蛮力法编写程序,输出这4件商品的价格分别是多少。

思路:蛮力(暴力)法

约束条件就2个,a+b+c+d=7.11,abcd=7.11。写3个for循环遍历出所有答案即可

坑点:C/C++浮点数误差分析

如上图,C语言的浮点数是有一定误差的,在误差范围内,我们一般默认实际值为正确答案

难点:

本题难点就在于如何解决该误差

方法1:

避免浮点数的计算

#include<iostream>
#include<math.h>
using namespace std;
/*711000000*/
/*2147483648*/
int main()
{
	double a,b,c,d;
	cout<<"a\tb\tc\td"<<endl;	
	for(a=1;a<711;a++)
	for(b=1;b<711;b++)
	for(c=1;c<711;c++)
 	{
  		d=711-(a+b+c);
  		if(a*b*c*d==711000000) 
  		{
 			cout<<a/100<<"\t"<<b/100<<"\t"<<c/100<<"\t"<<d/100<<endl;
  		}
 	}
 	return 0;
 }

方法2:

标明精度进行运算

#include<iostream>
#include<math.h>
using namespace std;
/*711000000*/
/*2147483648*/
int main()
{
	double a,b,c,d;
	cout<<"a\tb\tc\td"<<endl;	
	for(a=0.01;a<7.11;a=a+0.01)
	for(b=0.01;b<7.11;b=b+0.01)
	for(c=0.01;c<7.11;c=c+0.01)
 	{
  		d=7.11-(a+b+c);
  		if(fabs(a*b*c*d-7.11)<10e-8) 
  		{
 			cout<<a<<"\t"<<b<<"\t"<<c<<"\t"<<d<<endl;
  		}
 	}
 	return 0;
 }