C _ 求和函数没有给出期望的结果

标签 c

我一直在研究这个项目,但遇到了障碍。我完成了所有工作,但有一个细节在编译时无法正常工作。

You are to write a program that reads characters from the keyboard using the getch() function. All lower case letters will be converted to upper case and printed out to the display using the putchar() function. All uppercase letters will be printed using putchar(). All individual digits will be accumulated and the sum will be printed at the end of the program using printf(). You will write your own function to return the upper case of the letter, do not use the C library conversion functions, and a second function which receives the current sum using the current character digit, do not use the C library conversion functions. The convert digit function will convert the character digit to a decimal value and accumulate the digit to the sum returning the new sum. Only the letters will be printed out nothing else. The program will continue until the return is received at which time the sum of the digits will be printed on the next line. What was entered: a9 wF23’;/4i What the line actually shows: aAwWFiI The sum of the digits is: 18

我在下面发布了我已经完成的工作。除了需要对整数求和的部分(最初是字符但被转换)之外,该程序执行所有操作。它给了我一个非常大的数字,比 输入的数字。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define ctrlz 26

char cvttoupper(char);
int cvtdigit(int, char);

int main ()
{
    int sum, d;
    char c, cupper;
    sum = 0;
    do  
    {   
        c = getch();

        if (c>='A' && c<='Z' || c>='a' && c<='z' )
        {   
            putch(c);
            if(c>='a' && c<='z')
            {   
                cupper = cvttoupper(c);
                putch(cvttoupper(c));                                       
            }   
        }   
        if (c>='0' && c<='9')
        {   
            d=c&0x0F;             
            sum = cvtdigit(sum,c);                      
        }   
    }   while (c != ctrlz);

    printf("\nThe sum of the digits is: %d\n", sum);

    system ("PAUSE");
    return 0;
}

char cvttoupper(char c)
{
    char cupper;
    cupper= c & 0x5F;
    return (cupper);
}

int cvtdigit(int d, char c)
{
    int sum;
    sum=sum+d;
    return (sum);        
}

对于如何使求和部分正常工作的任何反馈,我们将不胜感激。我怀疑这是每个不正确的函数列出参数的方式。 (我必须自己创建函数,不能使用 C 库函数)。

谢谢。

最佳答案

问题出在你的 sum 函数上:

int cvtdigit(int d, char c)
{
    int sum;
    sum=sum+d;
    return (sum);        
}

main 中的原始sum 存储在d 中。您最终要做的是创建一个名为 num 的未初始化的新变量,添加 d 的值(即 sum in main) 到未初始化的 sum 并返回该值。这就是为什么您会收到奇怪的数字。

更改函数以删除 sum 并添加 d 的值(您应该将其重命名为 sum)和 c,首先从 c 中减去 '0',即字符 0 的字符代码,这样您就可以得到一个从 0 到 9 的值。

int cvtdigit(int sum, char c)
{
    sum=sum+(c-'0');
    return sum;
}

关于C _ 求和函数没有给出期望的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54931215/

相关文章:

C 字符串取消引用然后重新引用行为奇怪吗?

c - 确定性方式生成 char 数组

c++ - 链接包含具有等效签名的函数的几个 C 目标文件

我可以多次运行同一个线程吗?

c - 在 C 中获取当前语言环境的字符集?

c++ - 如何声明指向返回函数指针的函数的指针

c - 使用 posix 而不是 fork/execv 运行 bash

c - 意外的输入值; log10 失败

c - 这应该是 int,那我们为什么要使用 %s?

c - 如何从 Linux 帧缓冲区获取 RGB 像素值?