我的程序允许用户在文本文件中输入最多 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.");`
- 如何从函数中调用上面的代码?
- 我是否需要将所有整数存储在数组中并使用指针指向数组内的值?
关于如何进行的任何想法?
最佳答案
您所要做的就是将代码放入函数中,然后调用该函数。
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/