练习九O题分成整数问题

此题我们注意到的问题是三个数不能相等,不含数字3和7的情况。

代码如下:#include <iostream>

#include <bits/stdc++.h>

using namespace std;

int main()

{

int n,x,y,z;

cin >> n;

int a = 0;

for(x = 1;x <= n;x++)

{

for(y = 2;y <= n;y++)

{

z = n-x-y;

if(z > x && z > y && x != 3 && y != 3 && z != 3 && x != 7 && y != 7 && z != 7)

{

a++;

}

}

}

cout << a << endl;

return 0;

}

但编译出来的例子是正确的,答案是错误的,为什么?

因为我们忽略了数字本身就具有3,7;

所以我们要先进行数位提取个十百位,在main函数外调用一个函数,代码如下:

int worse(int b)

{

int c = b % 10;

int d = b / 10 % 10;

int e = b / 100 % 10;

if(c == 3 || c == 7 || d == 3 || d == 7 || e == 3 || e == 7)

return 1;

else

return 0;

}

如果提取的位数有3或者是7,退出,否则进入下一步,代码如下:

int main()

{

int n,x,y,z;

cin >> n;

int a = 0;

for(x = 1;x <= n;x++)

{

for(y = 2;y <= n;y++)

{

z = n-x-y;

if(worse(x) || worse (y) || worse(z))

continue;

if(z > x && z > y && y > x)

{

a++;

}

}

}

cout << a << endl;

return 0;

}

让x,y进行遍历,但请注意,y一定要比x大,跟排列组合原理差不多,x排完1,进入2,y就不能排1了;以此类推,最后if语句中要xyz进行比较就可以了;完整代码如下:

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

int worse(int b)

{

int c = b % 10;

int d = b / 10 % 10;

int e = b / 100 % 10;

if(c == 3 || c == 7 || d == 3 || d == 7 || e == 3 || e == 7)

return 1;

else

return 0;

}

int main()

{

int n,x,y,z;

cin >> n;

int a = 0;

for(x = 1;x <= n;x++)

{

for(y = 2;y <= n;y++)

{

z = n-x-y;

if(worse(x) || worse (y) || worse(z))

continue;

if(z > x && z > y && y > x)

{

a++;

}

}

}

cout << a << endl;

return 0;

}

全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 16:30
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务