鱼C论坛

 找回密码
 立即注册
查看: 4797|回复: 11

[已解决]求问这个应该怎么写?

[复制链接]
发表于 2021-7-12 20:53:44 | 显示全部楼层    本楼为最佳答案   
请问你是想要这个效果吗?  
  1. #include <stdio.h>
  2. typedef struct {
  3.   unsigned int jg0 : 1;
  4.   unsigned int jg1 : 1;
  5.   unsigned int jg2 : 1;
  6.   unsigned int jg3 : 1;
  7.   unsigned int jg4 : 1;
  8.   unsigned int jg5 : 1;
  9.   unsigned int jg6 : 1;
  10.   unsigned int jg7 : 1;
  11. } BIT;

  12. int main() {
  13.   BIT bit;
  14.   bit.jg0 = 0;
  15.   bit.jg1 = 1;
  16.   bit.jg2 = 1;
  17.   bit.jg3 = 1;
  18.   void * pbit = &bit;
  19.   printf("%d\n", (~(*(char*)pbit)+1)&(0xff>>4));

  20. // j3j2j1j0, 得到结果
  21. // 1 1 1 1, 1
  22. // 1 1 1 0, 2
  23. // 1 1 0 1, 3
  24. // 1 1 0 0, 4
  25. // ... 以此类推
  26. }
复制代码


上面采用的是C 语言中位域与二进制的运算特性实现的,常见于与硬件打交道的代码。占用的内存只需要四个字节、一个32位整型。大量的if...else...操作还可以用状态机实现。或者用哈希表也是一种比较现实的做法。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-7-13 14:01:56 | 显示全部楼层
fc5igm 发表于 2021-7-12 22:37
我的确是想要这种类似的效果,不过很可惜我不会c语言,另外这是用来做判别式的
  1. def fun(arr):
  2.     res = 0
  3.     for idx, val in enumerate(arr):
  4.         if(val == 1):
  5.             res = res + (1 << idx)
  6.     return 2**len(arr)-res
  7. '''
  8.     输入     输出 刚好等于2^4-输入的值
  9. j3 j2 j1 j0, res
  10. 1  1  1  1,  1  = 2^4-15
  11. 1  1  1  0,  2  = 2^4-14
  12. 1  1  0  1,  3  = 2^4-13
  13. 1  1  0  0,  4  = 2^4-12
  14. '''

  15. jg=[0,1,1]  # 注意数组元素左边为低右边为高
  16. print(fun(jg))
复制代码


我的这种做法一般来说可移植性不强,只针对于特定场合。上面是经过调整后的Python 代码,算是投机取巧了吧。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-7-15 23:09:16 | 显示全部楼层
fc5igm 发表于 2021-7-14 22:03
嗯。。貌似不是我想要的样子,不过还是选你吧。
这是我后来搞得代码

我试了你生成的代码,首先是生成的文件很大,运行起来比较卡,然后是在运行时,发现得不到期待的结果。
  1. print(verify(0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
  2. # 输出None
复制代码


我建议你还是试一试我这个,看哪里和预期不一样,然后再做调整:
  1. def fun(arr):
  2.     res = 0
  3.     for idx, val in enumerate(arr):
  4.         if(val == 1):
  5.             res = res + (1 << idx)
  6.     return 2**len(arr)-res

  7. jg=[jg0,jg1,...,jg20]  
  8. print(fun(jg))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-22 03:08

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表