【问题标题】:How do I create multiple answers in the output?如何在输出中创建多个答案?
【发布时间】:2018-09-07 05:10:45
【问题描述】:

我编写了一小段代码,用于计算给定数字 x 的方程。但是,当我想尝试复制此代码时,它不起作用。它说“重新声明没有链接的结果”。我想要做的是在控制台中输出 x=0、x=10 和 x=-10 时的输出。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>    
#include <math.h>
int main()
{
  float x = 0.0, result;
  result = 1/(1+exp(x));
  printf("Exponential of %f = %f", x, result);
  return 0;
}

它只适用于一个,但当我复制它时它就不起作用了。我想要做的只是复制它,因此它为控制台中的数字输出三个计算。谢谢

【问题讨论】:

  • 当询问有错误的代码时,您必须在问题中提供正确的minimal reproducible example,即产生错误的代码,以及逐字错误文本包括行号和发生错误的行中的可能位置。

标签: c output


【解决方案1】:

“重新声明”意味着您复制行

 float x = 0.0, result;

如果你只想从

float x = 0.0, result;
result = 1/(1+exp(x));
printf("Exponential of %f = %f", x, result);

计算不同x的结果,如下:

float x = 0.0, result; // declaration - only once
result = 1/(1+exp(x));
printf("Exponential of %f = %f", x, result);
x = 0.5; // new value for the same variable
result = 1/(1+exp(x)); // new value for the same variable
printf("Exponential of %f = %f", x, result);

还可以考虑制作循环以排除复制代码。常见的做法是这样的:

  1. 决定何时可以获取x 的值:它可以是用户输入的值,也可以是从startend 值范围内的值。
  2. 根据第 1 步的决定,您可以选择循环中的迭代次数以及停止循环的方法(条件)。
  3. 然后选择循环运算符:forwhiledo{}while 并编写代码。

【讨论】:

    【解决方案2】:
    float x = 0.0
    printf("Exponential of %f = %f\n", x, 1/(1+exp(x));
    
    x = 10.0
    printf("Exponential of %f = %f\n", x, 1/(1+exp(x));
    
    x = -10.0
    printf("Exponential of %f = %f\n", x, 1/(1+exp(x));
    

    【讨论】:

      【解决方案3】:

      在c语言中,不能重新声明变量,但可以重新赋值变量。

      试试这个:

      #include <stdio.h>
      #include <stdlib.h>
      #include <time.h>    
      #include <math.h>
      int main()
      {
        float x = 0.0, result;
        result = 1/(1+exp(x));
        printf("Exponential of %f = %f\n", x, result);
      
        x=10.0;
        result = 1/(1+exp(x));
        printf("Exponential of %f = %f\n", x, result);
      
        x=-10.0;
        result = 1/(1+exp(x));
        printf("Exponential of %f = %f\n", x, result);
      
        return 0;
      }
      

      希望这会有所帮助。

      【讨论】:

      • 您也无法重新初始化,但您可以重新分配
      • @AnttiHaapala 对不起,我的错。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2022-06-10
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多