我写了以下代码:
#include <stdio.h>
#include <stdlib.h>
void main (void) {
//------------------------ Variaveis------------------------//
char num[2];
int aux1, aux2, aux3;
//------------------------Parte grafica---------------------//
printf ("Escreva um numero de 0 a 99: ");
scanf ("%s", &num);
printf("\nEste numero por extenso eh: ");
//-------------------------Conversão------------------------//
aux1 = atoi(num);
aux2 = atoi(&num[0]);
aux3 = atoi(&num[1]);
不必介意语言,重点是,例如,如果您输入“ 56”之类的数字以使scanf读取,则aux2会获得“ 56”的值,而不是我想要的“ 5”,而aux3会获得的值“ 6”实际上是我所期望的。 aux2有什么问题?
最佳答案
通过为空终止符添加空间来修复未定义的行为后,让我们考虑程序的行为。
aux2
有什么问题?
由于atoi
会考虑整个字符串,因此aux2
与aux
相同,因为它是从'5'
开始并一直延续到'\0'
的字符串。
如果要获取单个数字,请使用'0'
减法:
int aux2 = num[0] - '0';
int aux3 = num[1] - '0';
确保
num
恰好有两个字符,并且两个字符均为数字。
关于c - 函数atoi返回错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49547464/