我正在开发一个类项目,我想做一些额外的工作并对我的数据进行验证。问题似乎发生在num1 = num1Input
(和num2 = num2Input
),它获取位置(我假设)而不是实际输入值
int main(void) {
//variables
char num1input[10];
char num2input[10];
int length, i;
int num1 = 0;
int num2 = 0;
int countErrors1 = 0;
int countErrors2 = 0;
bool correct1 = false;
bool correct2 = false;
//--end of variable declarations--//
do {
printf("Please enter a number: ");
scanf("%s", num1input);
length = strlen(num1input);
for (i = 0; i < length; i++) {
if (!isdigit(num1input[i])) {
countErrors1++;
}
}
if (countErrors1 > 0) {
printf("Input is not a number \n");
} else {
correct1 = true;
}
} while (correct1 == false);
num1 = num1input;
do {
printf("Please enter second number: ");
scanf("%s", num2input);
length = strlen(num2input);
for (i = 0; i < length; i++) {
if (!isdigit(num2input[i])) {
countErrors2++;
}
}
if (countErrors2 > 0) {
printf("Input is not a number \n");
} else {
correct2 = true;
}
} while (correct2 == false);
num2 = (int)num2input;
printf("%d %d \n", num1, num2);
int addition = num1 + num2;
int substraction = num1 - num2;
int multiplication = num1 * num2;
float division = num1 / num2;
printf("Addition: %d Subtraction: %d Multiplication: %d Division: %.1e", addition, substraction, multiplication, division);
getch();
}
答案 0 :(得分:1)
您无法将字符串转换为具有button
等强制转换的数字。您需要从num1 = num1input;
调用库函数:
<stdlib.h>
但是#include <stdlib.h>
...
num1 = atoi(num1input);
忽略了解析错误。为确保检测到溢出,您可以使用atoi
,如下所示:
strtol()
或者,如果您想识别十六进制语法,例如#include <errno.h>
#include <limits.h>
#include <stdlib.h>
...
errno = 0;
char *endp;
long lval = strtol(num1input, &endp, 10);
if (endp == num1input || errno != 0 || lval < INT_MIN || lval > INT_MAX) {
/* parse error detected:
* you could print an error message.
*/
if (lval < INT_MIN) lval = INT_MIN; /* clamp lval as an int value. */
if (lval > INT_MAX) lval = INT_MAX;
}
num1 = lval;
:
0x10
同样适用于num1 = strtol(num1input, NULL, 0);
。
请注意,如果num2input
已签名且isdigit(num1input[i])
的值为负,则char
可能不正确。你应该写:
num1input[i]
另请注意,isdigit((unsigned char)num1input[i])
将计算整数除法并将结果转换为float division = num1 / num2;
。如果你想要浮点除法,你应该写:
float
最后请注意,建议使用float division = (float)num1 / num2;
代替double
以提高准确性。
以下是更正后的简化版本:
float