c++水仙花数——变形题&详解pow()函数

这是一道求水仙花数的变形体:
描述:水仙花一朵x元,问有n元最多能买多少符合水仙花数朵水仙花?
输入:两个整数n(100<=n<=999),x(1<=x<=n)。
输出:输出符合要求的数,没有就输出-1。
说明:水仙花数:一个三位数其各位数字的立方和等于这个三位数。
例1:
输入:452 2
输出:153
例2:
输入:999 1
输出:407

#include<iostream>
using namespace std;
int main()
{
    int n,x;
    int ans=0,ams=0;
    cin >> n >> x;
    int m;
    m=n/x;
    int a,b,c;
    if(m<100)
    {
        cout << -1<<endl;
    }
    else if(m<1000)
    {
        for(int i=100; i<=999; i++)
        {
            a=i/100;
            b=i/10%10;
            c=i%10;
            int toal=a*a*a+b*b*b+c*c*c;
            if(toal==i)
            {
                ans=1;
                ams=i;
            }
        }
    }
    else
    {
        for(int i=100; i<=m; i++)
        {
            a=i/100;
            b=i/10%10;
            c=i%10;
            int toal=a*a*a+b*b*b+c*c*c;
            if(toal==i)
            {
                ans=1;
                ams=i;
            }
        }
    }
    if(ans==1)
    {
        cout << ams <<endl;
    }
    else
    {
        cout << -1<<endl;
    }
    return 0;
}

··································分····················割···············线·································································
这里是原型:
将所给两数范围内的所有水仙花数,从小到大依次输出。

#include<iostream>
#include<math.h>
using namespace std;
int SXH(int x)
{
	int B = x / 100, S = (x - B * 100) / 10, G = x % 10;
	if(x==pow(G,3)+pow(S,3)+pow(B,3))
		return 1;
	else return -1;
}
int main()
{
	int m, n;
	int a[4];
	int i = 0;
	while (cin >> m,cin >> n)
	{
		for (m; m <= n; m++)
		{
			if (SXH(m) == 1)
			{
				a[i] = m;
				i++;
			}
   	    }
		for (int j = 0; j < i; j++)
		{
			cout << a[j];
			if (j < i - 1)cout << ' ';
		}
		if(i>0)cout << endl;
		if (i == 0)
		{
			cout << "no" << endl;
		}
		i = 0;
	}
}

需要注意的是第二个原型题的代码中用到的pow函数:
头文件 :#include <math.h>
作用 :pow() 函数用来求 x 的 y 次幂(次方),x、y及函数值都是double型。
其原型为:double pow(double x, double y);
说明:
pow()用来计算以x 为底的 y 次方值,然后将结果返回。设返回值为 ret,则 ret = xy。

可能导致错误的情况:
如果底数 x 为负数并且指数 y 不是整数,将会导致 domain error 错误。
如果底数 x 和指数 y 都是 0,可能会导致 domain error 错误,这跟库函数实现有关。
如果底数 x 是 0,指数 y 是负数,可能会导致 domain error 或 pole error 错误,这也跟库函数实现有关。
如果返回值 ret 太大或者太小,将会导致 range error 错误。

错误代码:
如果发生 domain error 错误,那么全局变量 errno 将被设置为 EDOM;
如果发生 pole error 或 range error 错误,那么全局变量 errno 将被设置为 ERANGE。
Math.pow(底数,几次方)
如:
double a=2.0;
double b=3.0;
double c=pow(a,b);
c最终为8.0;

发布了4 篇原创文章 · 获赞 0 · 访问量 62

猜你喜欢

转载自blog.csdn.net/weixin_44772207/article/details/104508017
今日推荐