[英]int with atoi() calculated value is always 0
我正在創建一個程序來計算一次方程。 我的問題是,因為方程式將包含字符和操作數,所以我需要將日期存儲在字符串上,然后通過atoi()
將它們傳遞給整數。 然而,答案值永遠不會從 0(設定值)改變。 這是為什么?
這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
char equation[10];
scanf("%s", equation);
int length = strlen(equation);
char operands[7];
int op_index[7];
int op_amount = 0;
for(int i = 0; i < length; i++){
if(equation[i] == '*' || equation[i] == '/' || equation[i] == '+' || equation[i] == '-'){
operands[op_amount] = equation[i];
op_index[op_amount] = i;
op_amount++;
}
}
char nums1[3];
char nums2[3];
int i = op_index[0] - 1;
int j = 3;
int ans = 0;
while(isdigit(equation[i]) != 0){
nums1[j] = equation[i];
j--;
i--;
}
i = op_index[0] + 1;
j = 0;
while(isdigit(equation[i]) != 0){
nums2[j] = equation[i];
j++;
i++;
}
if(operands[0] == '*'){
ans = atoi(nums1) * atoi(nums2);
}
else if(operands[0] == '/'){
ans = atoi(nums1) / atoi(nums2);
}
else if(operands[0] == '+'){
ans = atoi(nums1) + atoi(nums2);
}
else if(operands[0] == '-'){
ans = atoi(nums1) - atoi(nums2);
}
printf("ans = %d", ans);
}
你太辛苦了。 或者,更確切地說,你讓計算機工作得太辛苦了。 您不需要(或不想)“將日期存儲在字符串上”。 您不需要復制該數據。 atoi
是一個損壞的工具(如果輸入不能用整數表示,則為未定義的行為),但它基本上可以做你想做的事。 不要四處復制數據,只需將您感興趣的字符串的第一個字符傳遞給它即可。以下代碼不能很好地處理無效數據(即,字符串“5 + + + 10”將被視為與“ 5 + 0" 和 "1foo +3x" 與 "1+3") 相同,但添加驗證輸入的邏輯留給讀者作為練習。 (提示:如果使用strtol
而不是atoi
,驗證輸入會容易得多。)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
char equation[1024];
int ans;
if( 1 != scanf("%1023[^\n]", equation) ){
fprintf(stderr, "No data avaialable\n");
return 1;
}
char *operator = equation + strcspn(equation, "*/+-");;
char *operand = operator + 1;
switch( *operator ){
case '*': ans = atoi(equation) * atoi(operand); break;
case '/': ans = atoi(equation) / atoi(operand); break;
case '+': ans = atoi(equation) + atoi(operand); break;
case '-': ans = atoi(equation) - atoi(operand); break;
default:
fprintf(stderr, "No operator found\n");
return 1;
}
printf("ans = %d\n", ans);
if( fflush(stdout) ){
perror("stdout");
return 1;
}
return 0;
}
請注意, scanf
絕對是此處獲取輸入的錯誤方式,將參數作為命令行參數會更有意義。 如果您確實從輸入 stream 中讀取,使用fgets
會更有意義。 但是我在這里保留scanf
是為了演示兩件事:您必須在%s
和%[
轉換上使用寬度修飾符以防止緩沖區溢出,並且您應該始終檢查返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.