c - 如何在不使用 stdlib.h 或 string.h 的情况下将数字转换为字符串?

这是我的练习:

编写一个函数,从用户那里接收两个显示两个实数(可能为负数)的字符串,并生成一个字符串,该字符串包含该字符串表示的大多数数字的整数部分。例如,给定字符串 2356.12 和字符串 243.5,程序必须创建字符串 2112.

void addstrings(char *snum1, char *snum2, char *res);

我需要创建这个函数,以及另外两个辅助函数

//  a function that receives a string that represents an actual number and returns the above number (that i succeed)
double stod(char *snum);
// A function that receives an integer and produces a string representing the number
void itos(long int num, char *snum);

addstrings 函数中使用的。

到目前为止,这是我的尝试:

void addstring(char *snum1, char *snum2, char *res) {
    stod(snum1);
    stod(snum2);

    *res = (long int)(*snum1 + *snum2);
}

double stod(char *snum) {
    int res = 0;
    for (int i = 0; snum[i] != '\0'; i++)
        res = res * 10 + snum[i] - '0';

    // return result.
    return res;
}

double itos(long int num, char *snum) {
    int i = 0;
    while (num) {
        snum[i++] = (num % 10) + '0';
        num = num / 10;
    }

    return (double)num;
}

int main() {
    char arr1[SIZE + 1];
    char arr2[SIZE + 1];
    char *res = NULL;
    int temp;

    gets(arr1);
    gets(arr2);

    addstring(arr1, arr2, res);

    printf("%d", addstring);

    return 0;
}

我在 addstring 函数中缺少什么?

回答1

您的问题和代码中有很多问题:

  • 编写一个函数,从用户那里接收两个显示两个实数(可能为负数)的字符串,这部分不清楚:您的意思是该函数应该读取用户输入并将其转换为 double values?

  • 并生成一个字符串,该字符串包含该字符串所代表的大多数数字的整数部分这也不清楚。从下一个短语看来,您应该输出 double values 的差值的整数部分。

  • double stod(char *snum); 可以使用 sscanf() 来实现。您的版本仅适用于正整数 values。

  • void itos(long int num, char *snum); 可以简单地使用 sprintf() 来实现。

  • addstrings 你不 store 返回 values 的 stod() 而是你添加字符串的第一个字符的 values 并且你 store 作为输出的第一个字符.

  • 你不应该使用 gets()

  • printf("%d", addstring); 不正确:您传递函数 addstring 的地址而不是返回 value。

这是一个更正的版本:

#include <math.h>
#include <stdio.h>

double stod(char *snum) {
    double d;
    if (sscanf(snum, "%lf", &d) == 1)
        return d;
    else
        return 0;
}

void itos(long int num, char *snum) {
    sprintf(snum, "%ld.", num);
}

void addstring(char *snum1, char *snum2, char *res) {
    double d1 = stod(snum1);
    double d2 = stod(snum2);
    long int diff = (long int)fabs(d1 - d2);
    itos(diff, res);
}

int main() {
    char arr1[32];
    char arr2[32];
    char res[32];

    if (scanf("%31s%31s", arr1, arr2) == 2) {
        addstring(arr1, arr2, res);
        printf("%s\n", res);
    }
    return 0;
}

相似文章

随机推荐

最新文章