[英]Solving a pair of equations in C - program giving odd results
首先,英語不是我的母語,所以我不確定我是否有正確的數學術語,因此我無法找到這個問題的任何以前的答案,如果這是重復的,請提前道歉.
無論如何,我需要用 C 編寫一個程序,用於求解格式為a*x + b*y = c
的一對方程,其中 x 和 y 在兩個方程中具有相同的值。 我使用的方法包括將第一個方程中的所有三個值(a、b 和 c)除以 a,然后將b*y
移動到方程的另一側,這樣我就可以得到一個方程,表示x = c - b*y
。 之后,我將 x 的值插入到第二個方程中,並從那里得到 y 的值,然后將其插入到第一個方程中並得到 x。
然而,我的代碼給出了奇怪的結果——例如,方程對 x + 3y = 25 和 2x − 5y = −27(因此,輸入為 1 3 25 2 -5 -27)給出了答案 -206 和-77 而不是 4 和 7 的正確答案。
我發布了整個代碼,因為它很短(<40 行),我不知道問題出在哪里:
#include<stdio.h>
void lin_jednacina2(float a1, float b1, float c1, float a2, float b2, float c2)
{
float x, y;
a1 = 1;
b1 = b1 / a1;
c1 /= a1;
b1 = -1 * b1;
b2 = b2 - a2 * b1;
c2 = c2 - a2 * c1;
y = c2 / b2;
x = c1 - b1 * y;
printf("\nThe values of x and y are %.2f and %.2f, respectively.", x, y);
return;
}
int main()
{
float a1, b1, c1, a2, b2, c2;
printf("Please enter the values of a, b and c for the first equation, in the format of ax + by = c. \n");
scanf("%f %f %f", &a1, &b1, &c1);
printf("Please enter the values of a, b and c for the second equation, in the format of ax + by = c. \n");
scanf("%f %f %f", &a2, &b2, &c2);
lin_jednacina2(a1, b1, c1, a2, b2, c2);
return 0;
}
你的算法有問題 - 似乎有些事情是不必要的除以 a1 ......
這工作正常:
void lin_jednacina2(float a1, float b1, float c1, float a2, float b2, float c2)
{
float x, y;
float b11 = b1 / a1;
float c11 = c1 / a1;
float a21 = a2 / a1;
y = (c2 - a21 * c1) / (b2 - a21 * b1);
x = c11 - b11 * y;
printf("\nThe values of x and y are %.2f and %.2f, respectively.", x, y);
return;
}
當然,您應該添加一些“保險絲”(零檢查)以防止被 0 除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.