#include <stdio.h>
typedef struct {
double low;
double high;
} fuzzy_set;
typedef struct {
fuzzy_set input_set;
fuzzy_set output_set;
} rule;
double membership(double value, fuzzy_set fs) {
if (value <= fs.low) return 0;
if (value >= fs.high) return 1;
return (value - fs.low) / (fs.high - fs.low);
}
double apply_rules(rule rules[], double input, int num_rules) {
double numerator = 0;
double denominator = 0;
for (int i = 0; i < num_rules; i++) {
double membership_degree = membership(input, rules[i].input_set);
double output_center = (rules[i].output_set.low + rules[i].output_set.high) / 2;
numerator += membership_degree * output_center;
denominator += membership_degree;
}
return (denominator != 0) ? (numerator / denominator) : 0;
}
int main() {
rule rules[] = {
{{0, 5}, {10, 20}},
{{3, 7}, {20, 30}},
{{6, 10}, {30, 40}}
};
int num_rules = sizeof(rules) / sizeof(rules[0]);
double test_input[] = {2.0, 4.0, 6.0, 8.0};
int num_inputs = sizeof(test_input) / sizeof(test_input[0]);
printf("Вхід | Вихід (дефаззифікація)\n");
for (int i = 0; i < num_inputs; i++) {
double output = apply_rules(rules, test_input[i], num_rules);
printf("%.1f | %.2f\n", test_input
[i
], output
); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+Cgp0eXBlZGVmIHN0cnVjdCB7CiAgICBkb3VibGUgbG93OwogICAgZG91YmxlIGhpZ2g7Cn0gZnV6enlfc2V0OwoKdHlwZWRlZiBzdHJ1Y3QgewogICAgZnV6enlfc2V0IGlucHV0X3NldDsKICAgIGZ1enp5X3NldCBvdXRwdXRfc2V0Owp9IHJ1bGU7Cgpkb3VibGUgbWVtYmVyc2hpcChkb3VibGUgdmFsdWUsIGZ1enp5X3NldCBmcykgewogICAgaWYgKHZhbHVlIDw9IGZzLmxvdykgcmV0dXJuIDA7CiAgICBpZiAodmFsdWUgPj0gZnMuaGlnaCkgcmV0dXJuIDE7CiAgICByZXR1cm4gKHZhbHVlIC0gZnMubG93KSAvIChmcy5oaWdoIC0gZnMubG93KTsKfQoKZG91YmxlIGFwcGx5X3J1bGVzKHJ1bGUgcnV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