chenxie95 / SJTU_C-_Cource

上交2022小学期 程序设计思想 答疑论坛
1 stars 0 forks source link

求助:结构体第四题矩阵 #23

Open jiucungg opened 2 years ago

jiucungg commented 2 years ago

结构体第四题矩阵:VSCode和ice上输出结果不一样。求助代码错在哪里?

代码如下:

#include <cstring>
#include<cmath>
#include <iostream> 
using namespace std;
const int  t = pow(10.0,9) + 7;
struct matrix
{
        int A[2][2];
};
matrix multiply_Mod(matrix x,matrix y); 
matrix fpower(matrix x, int n);

int main()
{
        int n;
        matrix origin;

        cin >> n;
        for (int i=0;i<2;i++)
        {
                for (int j=0;j<2;j++)
                cin >> origin.A[i][j];      
        }
        matrix ans = fpower(origin, n);
        for (int i=0;i<2;i++)
        {
                for(int j=0;j<2;j++)
                cout << ans.A[i][j] << " ";
                cout <<endl;
        }
    system("pause");
    return 0;

}
matrix multiply_Mod(matrix x,matrix y)//相乘后每个元素模 10^9+7 
{
       matrix temp;
       memset(temp.A,0,sizeof(temp.A));
       for(int i=0;i<2;i++)
       {
               for(int j=0;j<2;j++)
               {
                       for(int k=0;k<2;k++)
                       {
                               temp.A[i][j]+= x.A[i][k]*y.A[k][j] ;
                       }
                       temp.A[i][j] %= t;
               }
       }
       return temp;
} 
matrix fpower(matrix x, int n) {
    // 计算 x^n, 复杂度 O(log n)
    matrix ans;
    ans.A[0][0] = 1;
    ans.A[1][1] = 1;

    while (n) {
        if (n % 2) ans = multiply_Mod(ans,x);
        x = multiply_Mod(x,x);
        n /= 2;
    }
    return ans;
}
Liangzheng-ZL commented 2 years ago

是否使用VScode debug过

jiucungg commented 2 years ago

Vscode输出结果是正确的,但icce上是错误的·

chenxie95 commented 2 years ago

存在几个问题: 1 是数组初始化有问题; 2是输出格式多空格问题; 3. 后面的测试题中,当元素为负的情况下,取模应该是多少的问题;

jiucungg commented 2 years ago

谢谢老师,已经通过了