我试图将 2 个和从子程序传递回 C 中的主函数

如何解决我试图将 2 个和从子程序传递回 C 中的主函数

我目前正在尝试从两个不同的子程序中取一个总和并将其传递回主函数,但是每次我这样做时,它都会得到一个零值,我不确定为什么。我试过将我的打印语句放在主函数中,只是在子程序中进行计算,但仍然无效,所以我知道我的变量没有正确返回,我的总和是一个实际数字。如何将变量 sum 正确传递回主函数?

这是我的代码:

#include<stdio.h>

int X[2000];
int Y[2000];


int main()
{
   FILE*fpdata1= NULL;

   FILE*fpdata2 = NULL;

   fpdata1=fopen("DataSet1.txt","r");
   fpdata2=fopen("DataSet2.txt","r");

   if(fpdata1==NULL || fpdata2 == NULL)
   {
       printf("file couldn't be found");
   }

   int i=0;

   while(i<2000)
   {
       fscanf(fpdata1,"%d!",&X[i]);
       fscanf(fpdata2,&Y[i]);
      // printf("This is X: %d\n",X[i]);
      // printf("This is Y: %d\n",Y[i]);


       i++;
   }

    fclose(fpdata1);
   fclose(fpdata2);

   avgX(X);
   avgY(Y);

   float sum;
   float sumY;
   float totalsum;
   float totalavg;

   totalsum= sum + sumY;
   totalavg= totalsum/4000;

   printf("Sum X: %f\n\n",sum);


   printf("Total sum: %f\n\n",totalsum);

   printf("The total average is: %0.3f\n\n",totalavg);

   return 0;

}

int avgX(int X[])
{
    int i=0;
    float averageX;
    float sum;
    sum = 0;

    while (i<2000)
    {
        sum += X[i];
        i++;

    }
    averageX = sum/2000;

    printf("Sum of X: %f\n\n",sum);
    printf("The sum of Data Set 1 is: %0.3f\n\n",averageX);

      return(sum);



}


int avgY(int Y[])
{
    int i=0;
    float averageY;
    float sumY;
    sumY = 0;

    while (i<2000)
    {
        sumY += Y[i];
        i++;

    }
    averageY = sumY/2000;



    printf("Sum of Y: %f\n\n",sumY);
    printf("The sum of Data Set 2 is: %0.3f\n\n",averageY);
    return (sumY);



}

解决方法

首先,您似乎在期待这些台词

avgX(X);
avgY(Y);

以某种方式更新 sum 函数中的 sumYmain 变量。这是对内存访问方式的根本误解。

具有相同标识符的局部变量声明不会在函数之间共享。它们只能在声明它们的函数内访问(并且只能在函数调用期间访问)。

在此示例中,每个函数中的 apples 变量彼此绝对没有相关性。期望此程序打印 15 是错误的。该程序具有未定义行为,因为 foobar 从未初始化的变量中读取值。

void foo(void) {
    int apples;
    /* This is undefined behaviour,* as apples was never initialized. Do not do this. */
    apples += 5;
}   

void bar(void) {
    int apples;
    /* This is undefined behaviour,* as apples was never initialized. Do not do this. */
    printf("%d\n",apples);               
}                                         
                                  
                                  
int main(void) {
    int apples = 10;
    foo();
    bar();

    return 0;
}

取而代之的是,您需要使用函数的参数和返回值。在此示例中,在 main 中,我们将 applesvalue 作为参数传递给 foo5int foo(int val) { return value + 5; } void bar(int val) { printf("%d\n",val); } int main(void) { int apples = 10; apples = foo(apples); bar(apples); return 0; } 添加到此值,并且 返回结果。我们分配这个返回值,覆盖我们之前的值。

val

再次注意,foo 参数不引用某些“共享变量”,它们分别是 baravgX 的局部变量。


至于您的计划的细节:

  • 函数 avgYint sum_ints(int *values,size_t length) { int result = 0; for (size_t i = 0; i < length; i++) result += values[i]; return result; } 执行完全相同的操作,只是标识符不同。

最好编写一个带有附加长度参数的更通用的求和函数,这样您就不会到处对数据大小进行硬编码。

2000

然后您可以使用此函数轻松编写平均逻辑。

  • 您确实检查了您的文件指针是否无效,这很好,但您没有停止程序或以其他方式解决问题。

  • 假设一个文件总是准确地包含 fscanf 条目可能是幼稚的。您可以使用 2000 的返回值(即发生的转化次数)来测试您是否未能读取数据。它也用于表示错误。

  • 尽管全局变量被清零这一事实使您免于对未填充的数据进行潜在的操作(如果文件包含少于 int main(void) 个条目),它会如果有其他选择,最好避免使用全局变量。

  • 最好将文件的读取与自己的功能分开,这样可以针对每个文件处理故障,并且可以不受读取限制。

  • int main(int argc,char **argv)mainsum_ints 的正确有效签名。


综上所述,这里是您代码的大幅重构版本。请注意,当我们将 #include <stdio.h> #include <stdlib.h> #define DATA_SIZE 2000 int sum_ints(int *values,size_t length) { int result = 0; for (size_t i = 0; i < length; i++) result += values[i]; return result; } size_t read_int_file(int *dest,size_t sz,const char *fname) { FILE *file; size_t i; if ((file = fopen(fname,"r")) == NULL) { fprintf(stderr,"Critical: Failed to open file: %s\n",fname); exit(EXIT_FAILURE); } for (i = 0; i < sz; i++) if (fscanf(file,"%d!",dest + i) != 1) break; fclose(file); return i; } int main(void) { int data_x[DATA_SIZE] = { 0 },data_y[DATA_SIZE] = { 0 }; size_t data_x_len = read_int_file(data_x,DATA_SIZE,"DataSet1.txt"); size_t data_y_len = read_int_file(data_y,"DataSet2.txt"); float sum_x = sum_ints(data_x,data_x_len),sum_y = sum_ints(data_y,data_y_len); float total_sum = sum_x + sum_y; float total_average = total_sum / (data_x_len + data_y_len); printf("Sums: [X = %.2f] [Y = %.2f] [Total = %.2f]\n" "The total average is: %0.3f\n",sum_x,sum_y,total_sum,total_average); } 的整数返回值分配给浮点变量时,会发生 implicit conversion

import requests

from bs4 import BeautifulSoup

baseurl = 'https://www.everysize.com/'

headers = {
'User-Agent' : 'my user agent which i deleted for this'
 }

r = requests.get('https://www.everysize.com/sneaker-sale/')

soup = BeautifulSoup(r.content,'lxml')

productlist = soup.find_all('li',class_='item span3 reduced reduced--value loaded')

productlinks = [] 

 for item in productlist:
    for link in item.find_all('a',href=True):
    print(link['href'])

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地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-