根据用户输入创建函数

标签 c function

我的程序允许用户在文本文件中输入最多 10 个整数/字符。然后我正在使用:

            number = atoi(word);
            printf("\nstring  is \t %s\n", word);
            printf("integer is \t %d\n", number);

将输入的 char/int 从 ASCII 转换为整数。

示例:

输入:e 输出:字符串为 e,整数为 0

输入:10 输出:字符串为 10,整数为 10

我想要一个函数来显示所有用户输入的最小整数。我已经测试了下面的代码以给出最小的整数,但是这不包含在函数中。我无法创建一个每次都考虑不同数量的用户输入的函数。 p>

以下代码成功运行并返回我的最小整数:

    int minIndex = 0;
    int minNumber = INT_MAX;

    if (number <= minNumber)
    {
        minNumber = number;
        minIndedx = i;
    }
if (minIndex > 0)

    printf("min number is %d at position %d\n", minNumber, minIndex);
else
    printf("no numbers read in; hence: no minimum calculated.");`
  1. 如何从函数中调用上面的代码?
  2. 我是否需要将所有整数存储在数组中并使用指针指向数组内的值?

关于如何进行的任何想法?

最佳答案

您所要做的就是将代码放入函数中,然后调用该函数。

int minIndex = 0;           //Making Them Global Variables
int minNumber = INT_MAX;    //Making Them Global Variables
int i =  0;                 //Declaring And Initializing The Global 
                            //Variable i to keep count of the position.


number = atoi(word);
printf("\nstring  is \t %s\n", word);
printf("integer is \t %d\n", number);
min(number);  //Calling function min and passing it value of number


void min(int number){

    if (number <= minNumber){

         minNumber = number;
         minIndedx = i;
      }

    if (minIndex > 0)
    printf("min number is %d at position %d\n", minNumber, minIndex);

    else
    printf("no numbers read in; hence: no minimum calculated.");

    i++; //Every time Incrementing i to update position.
 }

在循环中运行程序,然后每次使用存储在变量 number 中的不同用户输入调用函数 min 时,如果传递给它的数字小于设置的值,则该函数最小值 ,它更新最小数字的值,这就是您获取用户输入的最小数字的方式。

注意:这不是一个有效的程序,您必须将其嵌入到您的代码中并更改它以满足您的需要。我无法做到这一点,因为我不知道你如何接受输入。

关于根据用户输入创建函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852176/

相关文章:

javascript - 使代码更小的函数

python - 通过 Python 调用的 C 函数确定错误的数组大小

c++ - 将 4 个套接字字节转换为一个 int

c - C 中带有 pthreads 的两个矩阵的乘积

c - 输出以一种奇怪的方式排序

javascript - JavaScript 中的 "function*"是什么?

java - 在不使用 Collection 作为返回类型的情况下从 java 函数返回多个值?

php - mysqli_real_escape_string 与数组在 php 中?

mysql - 将 PGSQL "Create Function"转换为 MySQL

c - 错误: assignment to expression with array type in c