gpt4 book ai didi

使用ascii的C代码频率表。

转载 作者:行者123 更新时间:2023-11-30 17:26:34 25 4
gpt4 key购买 nike

我对 C 编程比较陌生,这是我类的第六周,到目前为止我还没有遇到任何重大问题。我只是不知道我当前的作业是否出了问题,而且几个小时后就要到期。这是我到目前为止所拥有的。我正在使用 Visual Studio 2012。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char textChar;
int textLenght = 0;
int asciiArray[128] = {0};
int i;

int main()
{
printf("Enter a line of text: ");
scanf("%d", &textChar);

while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
printf("\nFREQUENCY TABLE\n");
printf("---------------\n");
printf("Char Count %% of Total\n");
printf("---- ----- ----------\n");
printf(" ALL %5d %9.2f%%\n", textLenght,( textLenght * 100.0 ) / textLenght );

for (i = 0; i < 128; i++)
if( asciiArray[textChar] != 0 )
printf("%c %d %9.2f%% \n",i+ "0",asciiArray[textChar]);

getchar();
getchar();
return 0;
}

现在我知道我的 for 循环中有一个问题,因为它没有显示,我只是不确定除此之外是否还有其他问题。非常感谢任何帮助,提前致谢。

最佳答案

这条线不对。

scanf("%d", &textChar);
  1. 我不清楚您想通过这一行实现什么目的。
  2. 当您使用 %d 作为格式说明符时,该函数将尝试读取整数并将其存储在给定地址。由于 textChar 的类型不是 int,因此您将立即遇到未定义的行为。

您应该使用 fgetc(stdin),而不是使用 getchar(它不是标准 C 库函数)。

fgetc() 返回一个 int。确保将 textChar 的类型更改为 int。

更改行:

printf("Enter a line of text: ");
scanf("%d", &textChar);

while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}

printf("Enter a line of text: ");

while ((textChar = fgetc(stdin))!= '\n') {
textLenght++;
asciiArray[textChar]++;
}

我将删除对 getchar() 的最后两次调用。它们似乎没有任何作用。

关于使用ascii的C代码频率表。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26728856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com