![](/img/trans.png)
[英]A Program for Simulating the Rolling of 2 Dice in C (How to fix my incorrect output?)
[英]How to fix output of truth table in C?
我正在嘗試在 c 中創建一個真值表,我已經構建了左側,因此我能夠在真值表中顯示輸入數字的所有可能性。 但我無法獲得真值表右側的正確 output。 我的意思是我們要求用戶寫 1 或 0,一旦我們讀完所有行,它應該在真值表的右側打印用戶的輸入。
例如:
row 0:1
row 1:0
row 2:0
row 3:0
row 4:1
row 5:1
row 6:0
row 7:0
Output 應該是這樣的
0, 0, 0, : 1
0, 0, 1, : 0
0, 1, 0, : 0
0, 1, 1, : 0
1, 0, 0, : 1
1, 0, 1, : 1
1, 1, 0, : 0
1, 1, 1, : 0
如您所見,用戶的輸入應該在真值表的右側
#include <stdio.h>
void increment(int truth_table[8][4], int f[8]){
for(int z=0; z<=1; z++){
for(int y=0;y<=1; y++){
for(int x=0; x<=1; x++){
for(int j = 0; j < 1; j = j + 1){
printf("%d %d %d : %d\n", z,y,x,f[j]);
}
}
}
}
}
void right_side(int truth_table[8][4], int f[8]){
for(int i = 0; i < 8; i = i + 1) {
for(int j = 0; j < 1; j = j + 1) {
printf("row %d:",j);
scanf(" %d", &f[j]);
}
}
increment(truth_table,f);
}
int main(void) {
int f[8];
int truth_table[8][4] = {0};
right_side(truth_table,f);
return 0;
}
問題出在最后一個j循環中,因為您只打印 0 和 1,但您想打印在 function void righ-side()中插入的數組元素
更新后的代碼如下:
#include <stdio.h>
void increment(int truth_table[8][4],
int f[8]){
for(int z=0; z<=1; z++){
for(int y=0;y<=1; y++){
for(int x=0; x<=1; x++){
// for(int j = 0; j < 8; j++){
printf("%d %d %d : ", z,y,x);
// }
printf("%d\n",f[record]);
++record;
}
}
}
}
void right_side(int truth_table[8][4],
int f[8]){
for(int i = 0; i < 8; i = i + 1) {
printf("row %d of F%d output variable:", i,i);
scanf(" %d", &f[i]);
}
increment(truth_table,f);
}
int main(void) {
int f[8];
int truth_table[8][4] = {0};
right_side(truth_table,f);
return 0;
}
沒有理由需要將其復雜化並拖入 2D arrays 等。這些是位,而不是int
。 我認為您正在尋找的 function 應該只是像這樣的直接表查找:
bool truthify (bool a, bool b, bool c)
{
const bool truth_table[] =
{
[0x00] = true,
[0x01] = false,
[0x02] = false,
[0x03] = false,
[0x04] = true,
[0x05] = true,
[0x06] = false,
[0x07] = false,
};
uint8_t index = a<<2 | b<<1 | c<<0;
return truth_table[index & 0x07];
}
測試代碼:
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
bool truthify (bool a, bool b, bool c)
{
const bool truth_table[] =
{
[0x00] = true,
[0x01] = false,
[0x02] = false,
[0x03] = false,
[0x04] = true,
[0x05] = true,
[0x06] = false,
[0x07] = false,
};
uint8_t index = a<<2 | b<<1 | c<<0;
return truth_table[index & 0x07];
}
int main (void)
{
for(size_t i=0; i<8; i++)
{
bool a = i&4;
bool b = i&2;
bool c = i&1;
printf("%d, %d, %d, : %d\n", a, b, c, truthify(a,b,c));
}
}
Output:
0, 0, 0, : 1
0, 0, 1, : 0
0, 1, 0, : 0
0, 1, 1, : 0
1, 0, 0, : 1
1, 0, 1, : 1
1, 1, 0, : 0
1, 1, 1, : 0
現在簡單地重寫它以獲取一些用戶輸入並將真值表作為參數傳遞給 function,然后你就是 go。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.