[英]Finding largest and smallest numbers using atoi
scanf("%1c%2c %d %d %d %d %d %d %d %d %d %d",
&x, &y, &arr[0], &arr[1], &arr[2], &arr[3], &arr[4],
&arr[5], &arr[6], &arr[7], &arr[8], &arr[9]);
strcpy(string, x);
value1 = atoi(string);
strcpy(string, y);
value2 = atoi(string);
value_final = value1 + value2;
I'm trying to get the ascii values for the -l
or -s
then pass them through the switch
with the ascii values added but I'm getting errors when I use atoi
and I'm not sure as to if you are supposed to be adding the ascii values when the user enters the -l
or -s
or if their is another way to do this? 我正在尝试获取
-l
或-s
的ascii值,然后将它们通过添加了ascii值的switch
传递,但是我在使用atoi
时遇到错误,并且不确定是否应该使用当用户输入-l
或-s
或如果它们是另一种方式时,添加ascii值?
Your code has several problems: 您的代码有几个问题:
switch
cases do not have a break;
switch
盒没有break;
clause. default
statement. default
语句。 char
arrays and single char variables: strcpy(string, x);
char
数组和单个char变量之间的显示混乱: strcpy(string, x);
should not even compile. -l
or -s
is very convoluted and probably erroneous. -l
或-s
方法非常复杂,并且可能是错误的。 You should use character literals. printf
statement should be outside the loop. printf
语句应该在循环之外。 max
and min
are uninitialized, the loops invoke undefined behavior. max
和min
未初始化,循环调用未定义的行为。 atoi()
: if this was your assignment, you should not use scanf()
. atoi()
:如果这是您的工作,则不应使用scanf()
。 Here is a simplified version: 这是一个简化的版本:
int main(void) {
char option[3], buffer[32];
int i, min, max, value;
min = max = 0;
if (scanf("%2s", option) == 1) {
for (int i = 0; i < 10 && scanf("%31s", buffer) == 1; i++) {
value = atoi(buffer);
if (i == 0) {
min = max = value;
} else {
if (min > value)
min = value;
if (max < value)
max = value;
}
}
if (!strcmp(option, "-l")) {
printf("output: The largest number is %d\n", max);
return 0;
} else
if (!strcmp(option, "-s")) {
printf("output: The smallest number is %d\n", min);
return 0;
}
}
printf("You have entered an invalid option, try again next time.\n");
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.