gpt4 book ai didi

c - 如何生成具有相同字符数的单词数?

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:15 26 4
gpt4 key购买 nike

我正在通过 k&r 学习 c 编程语言,我遇到了这个练习“编写一个程序来打印其输入中单词长度的直方图。很容易绘制带有水平条的直方图;垂直方向是更具挑战性”,我决定对问题做一些修改,这就是我到目前为止所得到的:

 #include <stdio.h>
#define OUT 0
#define IN 1
main(){
int c, nw, nc, i,state,j;
nw = nc = 0;

while ((c = getchar()) != EOF){
if (c == '\n' || c == '\t' || c == ' ')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}


if (state == IN) {
if (c >= 'a' && c <= 'z')
++nc;
if ( c >='0' && c<='9')
++nc;
}
}
printf("Lengths of words");
for (j = 1; j < 10; ++j){
printf("[%d]-%d", j, nw);
}
}

所以这就是我希望计算机打印出的内容:

 Lengths of words
[0]- nw with > 10 characters
[1]- nw with 1 character
[2]- nw with 2 characters
[3]- nw with 3 characters
...

例如:我的名字是 linh 它将打印以下内容:

[0]- 0
[1]- 0
[2]- 2
[3]- 0
[4]- 0
...

我知道这个练习是关于数组的,因此,我可能在这个程序中遗漏了它的概念,需要有人来纠正我:)我很想知道我怎样才能用相同数量的字符。另外,我希望我的代码能以某种方式被审查……我相信其中存在一些误解。我是 C 语言的新手,非常感谢您的任何帮助 :) 提前致谢!

最佳答案

我试图解决你的问题。我希望它能对您有所帮助,而且对您来说足够简单明了。

 #include <stdio.h>

typedef int bool;
#define true 1
#define false 0
#define maxNumOfWords 10

char *createHistogram(int n) {
char *hist = (char *)malloc((n + 1) * sizeof(char));
if (hist == NULL) {
return "";
}
int i = 0;
for (i = 0; i < n; i++) {
hist[i] = '*';
}
hist[i] = '\0';
return hist;
}

int main(int argc, char *argv[]) {
bool isInWord = false;
int results[maxNumOfWords];
int index = -1;
int j;
char c;

// initialize the result array to 0
for (j = 0; j < maxNumOfWords; j++) {
results[j] = 0;
}
while ((index < maxNumOfWords) && ((c = getchar()) != EOF)) {
switch (c) {
case '\n':
case '\r':
case '\t':
case ' ':
isInWord = false;
break;
default:
// on the beginning of the first word
if (isInWord == false) {
++index;
}
isInWord = true;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
results[index] += 1;
break;
}
}
printf("Lengths of words:\n");
for (j = 0; j < maxNumOfWords; j++) {
int n = results[j];
printf("[%d]-%d %s\n", j, n, createHistogram(n));
}
}

关于c - 如何生成具有相同字符数的单词数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728853/

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