C 多项式加法练习

如何解决C 多项式加法练习

我目前正在做算法课的练习。我被要求编写一个 C 程序,将用户输入的两个多项式相加,我可以通过询问用户每个多项式的最高次数及其系数来实现。

问题是用户的输入必须是例如-5x4+2x2+6(所有系数和度数都可以从09)。

我设法将此字符串转换为数组

void tableau(char *chaine) {
    int i = 0;
    while (1) {
        scanf("%c",&chaine[i]);
        if (chaine[i] == '\n') {
            break;
        } else {
            i++;
        }
    }
}

我创建了一个结构

struct polynome {
    int coeff;
    int degre;
};

我找不到将这个数组转换为多项式的方法,这里是我编写的所有函数以使其工作,但我总是得到奇怪的输出:

int DEGREMAXTAB(char TAB[]) {
    int i = 0;
    int degre0 = 0;
    while (TAB[i] != '\0') {
        if (TAB[i] == 'x' && (int)(TAB[i+1]) > degre0)
            degre0 = (int)(TAB[i+1]);
        i++;
    }
    return degre0; // it returns the right highest degree + 48 for some reason,I don't know
}

void tabpoly(char chaine[],int degre0,struct polynome polynome[]) {
    int k = 1;
    int i = 0,a = 0,b = 0;
    
    while (chaine[i]) { // I am sorry,all of this is really messy,I just tried
        if (chaine[i] == '\0')
            break;
        
        if (chaine[i] == '-') {
            k = -1;
            i++;
        }
        if (chaine[i] == '+') {
            k = 1;
            i++;
        }
        if (chaine[i] != 'x') {
            a = k * ((int)(chaine[i]));
            i++;
        }
        i++;
        b = ((int)(chaine[i]));
        polynome[degre0].coeff = a;
        polynome[degre0].degre = b;
        degre0++;
        i++;
    }
}

void afficher(struct polynome poly[],int degre0) { /* maybe something is wrong here too I
really can't find the issue except by tweaking everything and causing other issues */
    int i = 0;
    char signe;
    for (i = degre0; i >= 0; i--) {
        if (poly[i].coeff < 0) {
            signe = '\0';
        } else {
            signe = '+';
        }
        printf("%c%dx%d",signe,poly[i].coeff,poly[i].degre);
    }
}

到目前为止我的主要内容:

int main(int argc,const char *argv[]) {
    struct polynome poly1[6]; // the maximum degree is 5
    int deg1 = 0,i = 0;
    char chainea[21];
    printf("Entrez votre premier polynôme\n");
    tableau(chainea);
    while (chainea[i] != '\0') {
        printf("%c",chainea[i]);
        i++;
    } // did this to check that there was no problem here
    
    deg1 = DEGREMAXTAB(chainea);
    printf("%d\n",deg1); // same,except that I must return deg1-48 and idk why
 
    tabpoly(chainea,deg1,poly1);
    afficher(poly1,deg1);   
}

我知道我的代码可能真的很乱,对此我深表歉意,如果有人能帮我解决这个问题,我会很高兴。这是我输入示例中的输入时的输出。

Entrez votre premier polynôme
-5x4+2x2+6
-5x4+2x2+6
4
-101x4+0x0+0x0+0x0+0x1Program ended with exit code: 0


Entrez votre premier polynôme
2x2
2x2
2
+2x2+0x0+0x1Program ended with exit code: 0

非常感谢,我尽量提供尽可能多的信息。 :)

解决方法

我找到了一个解决方案,但度数显示为倒数;常数是第一项。指数用作多项式的次数。 enter image description here

#include <stdio.h>

struct poly {
    int coef[9];
};

struct poly add(struct poly P1,struct poly P2) {
    struct poly result;
    for (int i = 0; i < 9; i++) {
        result.coef[i] = P1.coef[i] + P2.coef[i];
    }
    return result;
}
   
void display(struct poly P) {
    printf("%d + %dx",P.coef[0],P.coef[1]);
    for (int i = 2; i < 9; i++) {
        printf(" + %dx%d",P.coef[i],i);
    }
    printf("\n");
}
  
int main() {
    struct poly p1,p2,result;
    printf("Enter coefficients in order[Po 1]: ");
    for (int i = 0; i < 9; i++) {
        scanf("%d",&p1.coef[i]);
    }
    printf("Enter coefficients in order[Po 2]: ");
    for (int i = 0; i < 9; i++) {
        scanf("%d",&p2.coef[i]);
    }
    result = add(p1,p2);
    printf("\nThe Result is ");
    for (int i = 0; i < 9; i++) {
        printf("%d ",result.coef[i]);
    }
    printf("\n");
    display(result);
    return 0;
}
,

@sadbro:你的回答有问题:

  • 系数数组的长度应为 10,循环应运行到 i <= 9i < 10。甚至更好:将 MAX_POWER 定义为 9 并在 for 循环的数组大小中使用它。
  • 如果系数按升序输入,则输出循环应从最高指数向下迭代到 0
  • 不应打印具有 0 系数的单项式。
  • 您不应打印等于 1-1 的系数。
  • 您应该打印没有前导 + 的负系数。
  • 更一般的做法是不在 display() 中打印尾随换行符。

这是修改后的版本:

#include <stdio.h>

#define MAX_POWER  9

struct poly {
    int coef[MAX_POWER + 1];
};

struct poly add(struct poly P1,struct poly P2) {
    struct poly result;
    for (int i = 0; i <= MAX_POWER; i++) {
        result.coef[i] = P1.coef[i] + P2.coef[i];
    }
    return result;
}

// return the number of bytes printed
int display(struct poly P) {
    int pos = 0;
    for (int i = MAX_POWER; i >= 0; i--) {
        int coefficient = P.coef[i];
        const char *prefix = "";
        if (coefficient != 0) {
            if (pos) {
                if (coefficient > 0) {
                    prefix = " + ";
                } else {
                    prefix = " - ";
                    coefficient = -coefficient;
                }
            } else {
                if (coefficient < 0) {
                    prefix = "-";
                    coefficient = -coefficient;
                }
            }
            pos += printf("%s",prefix);
            if (coefficient != 1) {
                pos += printf("%d",coefficient);
            }
            if (i > 1) {
                pos += printf("x%d",i);
            } else
            if (i == 1) {
                pos += printf("x");
            }
        }
    }
    if (pos == 0) {
        pos += printf("0");
    }
    return pos;
}
  
int main() {
    struct poly p1,result;
    printf("Enter coefficients in order[Po 1]: ");
    for (int i = 0; i <= MAX_POWER; i++) {
        if (scanf("%d",&p1.coef[i]) != 1)
            return 1;
    }
    printf("Enter coefficients in order[Po 2]: ");
    for (int i = 0; i <= MAX_POWER; i++) {
        if (scanf("%d",&p2.coef[i]) != 1)
            return 1;
    }
    result = add(p1,p2);
    printf("\nThe Result is");
    for (int i = 0; i <= MAX_POWER; i++) {
        printf(" %d",result.coef[i]);
    }
    printf("\n");
    display(result);
    printf("\n");
    return 0;
}
,

您的代码中存在多个问题:

  • 您应该使用简单的 fgets() 读取多项式,而不是使用 scanf() 一次读取一个字符。 scanf() 不是最好的工具。
  • 获得 48 偏移量的原因是数字是 ASCII 字符,而不是整数值。您必须减去 '0' 的值(作为 ASCII 中的值 48)才能得到相应的数字。
  • 当您访问 poly 数组中超出最大索引值的元素时,您会遇到未定义的行为,因为偏移量为 48。您应该检查指数是否在适当的范围内。
  • 您会得到随机值,因为 poly 数组未初始化。

这是修改后的版本:

#include <stdio.h>

struct polynome {
    int coeff;
    int degre;
};

int degremaxtab(const char tab[]) {
    int i,exp,max_exp = 0;
    for (i = 0; tab[i] != '\0'; i++) {
        if (tab[i] == 'x') {
            i++;
            if (tab[i] >= '0' && tab[i] <= '9') {
                exp = tab[i] - '0';
            } else {
                exp = 1;
            }
            if (max_exp < exp) {
                max_exp = exp;
            }
        }
    }
    return max_exp;
}

int skip_spaces(const char chaine[],int i) {
    while (chaine[i] == ' ' || chaine[i] == '\t' || chaine[i] == '\n') {
        i++;
    }
    return i;
}

/* return the maximum exponent in the polynomial */
int tabpoly(const char chaine[],struct polynome polynome[],int max_degree) {
    int i,max_exp,sign,coeff,exp;

    for (i = 0; i <= max_degree; i++) {
        polynome[i].coeff = 0;
        polynome[i].degre = i;
    }

    i = 0;
    max_exp = 0;
    while (chaine[i] != '\0') {
        i = skip_spaces(chaine,i);
        // get sign (allow +-)
        sign = 1;
        if (chaine[i] == '+') {
            i++;
        }
        i = skip_spaces(chaine,i);
        if (chaine[i] == '-') {
            sign = -1;
            i++;
        }
        i = skip_spaces(chaine,i);
        if (chaine[i] >= '0' && chaine[i] <= '9') {
            coeff = chaine[i] - '0';
            i++;
        } else {
            coeff = 1;
        }
        if (chaine[i] == 'x') {
            i++;
            if (chaine[i] >= '0' && chaine[i] <= '9') {
                exp = chaine[i] - '0';
                i++;
            } else {
                exp = 1;
            }
        } else {
            exp = 0;
        }
        i = skip_spaces(chaine,i);

        // check for a complete term
        if (chaine[i] != '\0' && chaine[i] != '+' && chaine[i] != '-')
            return -2;  // syntax error
        if (exp > max_degree)
            return -1;  // exponent too large
        if (max_exp < exp)
            max_exp = exp;
        polynome[exp].coeff += sign * coeff;
    }
    return max_exp;
}

void afficher(struct polynome poly[],int degre0) {
    int i,pos;
    /* simple output */
    for (i = degre0; i >= 0; i--) {
        printf("%+dx%d",poly[i].coeff,poly[i].degre);
    }
    printf("\n");
    /* clean output */
    pos = 0;
    for (i = degre0; i >= 0; i--) {
        int coeff = poly[i].coeff;
        int degre = poly[i].degre;
        if (coeff != 0) {
            if (coeff > 0) {
                if (pos > 0)
                    pos += printf("+");
                if (coeff != 1 || degre == 0)
                    pos += printf("%d",coeff);
            } else {
                if (coeff != -1 || degre == 0)
                    pos += printf("%d",coeff);
                else
                    pos += printf("-");
            }
            if (degre > 0) {
                printf("x");
                if (degre > 1)
                    pos += printf("%d",degre);
            }
        }
    }
    if (pos == 0) {
        printf("0");
    }
    printf("\n");
}

int main(int argc,const char *argv[]) {
    struct polynome poly1[6]; // the maximum degree is 5
    char chainea[100];
    int deg1;

    printf("Entrez votre premier polynôme\n");
    // read a full line from stdin
    if (!fgets(chainea,sizeof(chainea),stdin))
        return 1;

    deg1 = degremaxtab(chainea);
    printf("exposant maximum: %d\n",deg1);

    deg1 = tabpoly(chainea,poly1,5);
    if (deg1 < 0) {
        if (deg1 == -1)
            printf("exposant trop grand\n");
        else
        if (deg1 == -2)
            printf("erreur de syntaxe\n");
        else
            printf("erreur\n");
    } else {
        afficher(poly1,deg1);
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res