ปัญหา: แก้สมการเชิงเส้นตัวแปรเดียว ax + b = 0
รับค่า a, b คำนวณ x = -b/a (ถ้า a != 0)
อัลกอริทึม
- อ่าน a, b
- ถ้า a == 0 แสดงข้อความไม่สามารถคาดการณ์ค่าได้
- มิฉะนั้น คำนวณ c = -b / a คืนค่า c
โค้ด C
#include <stdio.h>
#include <string.h>
float solve(float a, float b) {
float c;
if (a == 0) {
printf("value of c cannot be predicted\n");
} else {
c = -b / a;
}
return c;
}
int main() {
float a, b, c;
printf("\n enter a,b values: ");
scanf("%f%f", &a, &b);
c = solve(a, b);
printf("\n linear eq of one variable in the form of ax+b = 0, if a=%f,b=%f,then x= %f", a, b, c);
return 0;
}
ตัวอย่าง Output
enter a,b values: 4 8
linear eq of one variable in the form of ax+b = 0, if a=4.000000, b=8.000000, then x= -2.000000