Solve equations using iterative methods

Solve equations using iterative methods

#include <stdio.h>
#include <stdlib.h>
int n = 3;//3阶行列式
double sum(int i,int a[3][3],double x0[3]){
    
    
    double result = 0.0;
    for(int j = 0 ; j < n ; j++){
    
    
        if( j != i){
    
    
            result += a[i][j] * x0[j];
        }
    }

    return  result;
}
int main(){
    
    

    int A[3][3] = {
    
    -22, 11, 1, 1, -4, 2, 11, -3, -33};
    int b[3] = {
    
    0, 1, 1};
    //输出A和b
    printf("A:\n");
    for(int i = 0; i < n; i++){
    
    
        for(int j = 0; j < n; j++){
    
    
            printf("%d\t", A[i][j]);
        }
        printf("\n");
    }
    printf("b:\n");
    for(int i = 0; i < n; i++){
    
    
        printf("%d\t", b[i]);
    }
    printf("\n");
//  double e;
    double x0[3] = {
    
    0,0,0};//初始化向量
    double t[3] = {
    
    0,0,0};//临时变量
    double x[3] = {
    
    0,0,0};//k+1
    int times = 20;//迭代次数
    for(int  k = 0; k < times; k++){
    
    
        for(int i = 0; i < n; i++){
    
    

        x[i] =  (b[i] - sum(i,A,x0)) / A[i][i] ;
        t[i] = x[i];

        }
        printf("\n第%d次迭代:\n",k+1);
        for(int j = 0; j < n; j++){
    
    
            x0[j] = t[j];
            printf("x0[%d]=%.6lf\n",j,t[j]);
        }   //更新x0里的值并输出
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/106664360