我正在尝试创建一个程序,该程序使用户能够计算两个给定集合的差和笛卡尔乘积。我已经能够找到不同的套子。
我在编写用于计算两个集合的笛卡尔积的代码时遇到麻烦,即集合1 = {1,2
和集合2 = 3,4
我到目前为止编写的用于计算笛卡尔积的差和一半的计算的程序如下:
#include <stdio.h>
#include <conio.h>
main() {
int i, j, k, p, ch, n1, n2, set1[10], set2[10], set3[20], flag;
int wish;
printf("\n Enter the size of sets1 \n");
scanf_s("%d", &n1);
printf("\n Enter the element of set1 \n");
for (i = 0; i < n1; i++)
scanf_s("%d", &set1[i]);
printf("\n Enter the size of sets2 \n");
scanf_s("%d", &n2);
printf("\n Enter the elements of set2 \n");
for (i = 0; i < n2; i++)
scanf_s("%d", &set2[i]);
do {
printf("\n Menu for set operations");
printf("\n press 1 for DIFFERENCE");
printf("\n press 2 for CARTESIAN PRODUCT");
printf("\n Enter your Choice");
scanf_s("%d", &ch);
switch (ch) {
case 1://for difference
k = 0;
for (i = 0; i < n1; i++) {
flag = 1;
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
flag = 0;
break;
}
}
if (flag == 1) {
set3[k] = set1[i];
k++;
}
}
p = k;
for (k = 0; k < p; k++) {
printf(" %d", set3[k]);
}
break;
case 2: //for cartesian product
k = 0;
for (i = 0; i < n1; i++) {
flag = 1;
for (j = 0; j < n2; j++) {
}
}
}
printf("\n Do you want to continue(0/1)? ");
scanf_s("%d", &wish);
} while (wish == 0);
getch();
}
答案 0 :(得分:1)
只需添加printf("{%d, %d}, ", set1[i], set2[j]);
即可打印cartesian
产品。您应该使用scanf
而不是scanf_s
Difference between scanf and scanf_s
以{} {} {} ...格式打印结果
case 2: //for cartesian product
/*
A={1,2} and B={3,4}
Cartesian product of A and B is A x B = {{1,3},{1,4},{2,3},{2,4}}
*/
for (i = 0; i < n1; i++)
{
for (j = 0; j < n2; j++)
{
//print cartesian product of two set
printf("{%d, %d} ", set1[i], set2[j]);
}
}
以{{},{},...}格式打印结果
case 2: //for cartesian product
printf("{");
for (i = 0; i < n1; i++)
{
for (j = 0; j < n2; j++)
{
if(i==n1-1 && j==n2-1)
printf("{%d, %d} ", set1[i], set2[j]);
else
printf("{%d, %d}, ", set1[i], set2[j]);
}
}
printf("}");