c - 函数atoi返回错误的数字

标签 c

我写了以下代码:

#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会考虑整个字符串,因此aux2aux相同,因为它是从'5'开始并一直延续到'\0'的字符串。

如果要获取单个数字,请使用'0'减法:

int aux2 = num[0] - '0';
int aux3 = num[1] - '0';


确保num恰好有两个字符,并且两个字符均为数字。

关于c - 函数atoi返回错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49547464/

相关文章:

c - gdb 无法运行带有 "File format not recognized"的 ELF 64 位程序

c++ - 用 OpenGL 模糊?

c++ - 注册每个 C/C++ 源文件以创建已用源的运行时列表

c - SSL_CONNECT 因 SSL_ERROR_SYSCALL 错误而失败

c++ - 如何使用 pthread_setaffinity_np

c - 从 C 程序返回值是什么意思?

c - 从任何方法返回 const 或最终值/引用的优点/缺点

c - 给学生打分

c - 如何在 chroot jail 中执行 shell 命令

c++ - AIX:_snw(unsigned long) 中的 malloc?