Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หาคำตอบสมการเชิงเส้น ax + b = 0

ปัญหา: แก้สมการเชิงเส้นตัวแปรเดียว ax + b = 0

รับค่า a, b คำนวณ x = -b/a (ถ้า a != 0)

อัลกอริทึม

  1. อ่าน a, b
  2. ถ้า a == 0 แสดงข้อความไม่สามารถคาดการณ์ค่าได้
  3. มิฉะนั้น คำนวณ 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