【问题标题】:How to make a C program that takes input of integers, and prints the input with the largest number?如何制作一个接受整数输入并打印最大数字的输入的 C 程序?
【发布时间】:2014-10-30 23:37:44
【问题描述】:

我将如何制作一个 C 程序来接收用户的输入(整数,如 -232 或 14)并打印用户输入的最大值的整数?

目前我只知道(我的伪代码):

int main(void)
{

    int variable;

    printf("Enter an integer to check if that is the greatest integer you inputted.")

    if %d > variable;
        printf("The greatest value you entered is %d")
    elif
        printf("The greatest value you entered is 'variable'")

    scanf("%d", &variable) /Will this command help? IDK
}

我不想要实际的代码,但我需要这样做的步骤/命令。 很抱歉让我看起来好像在让别人为我做我的工作。 我刚开始C,对它不是很熟悉:(

谢谢。

PS 该程序应该存储并记录输入的最大整数。

【问题讨论】:

  • MIN and MAX in C的可能重复
  • 你所拥有的并不是真正的伪代码,而是非常糟糕的 C 代码。如果您不熟悉 C,我建议您阅读在线教程或获取介绍性 C 书籍。正如@McLovin 建议的那样,您将需要一个循环(在C 中,while 可以在这里工作)。您需要从 variable 初始化为可能的最低值开始,或者有一个单独的标志来指示您是否已经读取了第一个值。在循环中,只要大于variable,就将variable 替换为下一个读取的整数。当没有更多输入时循环结束。然后你打印variable
  • 用户输入一个整数吗?那应该和什么比较呢?

标签: c if-statement numbers integer compare


【解决方案1】:

你需要两件东西,一件是你正在寻找的东西,一件是你的最终情况(你什么时候停止寻找)

您正在寻找最大的数字,但什么时候停止寻找?在 10 个值之后?文件结束后?换行后?

所以在伪代码中是这样的

int i = 0;
int variable = 0; //Good practice to initialize your variables.
while(When will you stop? i < 10 eg 10 inputs?){
    if(your input is > variable){
        variable = input;
    }
i++; //or whatever your end case is. Have to get closer to the end case.
return variable;

【讨论】:

    【解决方案2】:
    #include <limits.h>
    #include <stdio.h>
    
    int main(void)
    {
        int greatest = INT_MIN, variable;
        FILE *fp;
        (fp = fopen("record.txt", "a")) &&
        (fp = freopen("record.txt", "r+", fp));
        if (!fp) return perror("record.txt"), 1;
    
        fscanf(fp, "%d", &greatest);
        printf("Enter an integer to check if that is"
               " the greatest integer you inputted. ");
        if (scanf("%d", &variable) == 1)
          if (variable > greatest)
              rewind(fp), fprintf(fp, "%d\n", greatest = variable);
        printf("The greatest value you entered is %d\n", greatest);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-09
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多