c - C中的字符计数器
问题描述
这段 C 语言代码应该计算表中等于 A 的所有字符..但它不起作用我需要帮助才能找到问题!~~我首先使用for循环读取用户给出的表格字符,然后我使用另一个for循环来计算等于A的字符数~~
请有任何建议
#include <stdio.h>
#include <stdlib.h>
int main()
{
char T[100],A;
int i,N,b=0;
printf("give the number of your table's columns \n");
scanf("%d", &N);
if (N > 0 && N <= 100) {
for (i; i < N; i++) {
scanf("%c", &T[i]);
printf("give the character of the column number %d \n", i);
scanf("%c",&T[i]);
}
for (i; i < N; i++) {
if (T[i] = 'A') b++;
printf("the number of characters equal to A is %d",b);
}
return 0;
}
}
解决方案
“应该计算一个表中所有等于 A 的字符 ..但它不起作用我需要帮助才能找到问题!!”
编译器警告将帮助您找到问题所在。
如果您在编译时没有看到警告,请将您的编译器设置为显示它们。(例如在 GCC中使用-Wall
)
在打开警告的情况下进行编译时,您应该会在编译时看到与此类似的信息:
Build Status (so.prj - Debug)
s0_15.c - 3 warnings
22, 22 warning: using the result of an assignment as a condition without parentheses
22, 22 note: place parentheses around the assignment to silence this warning
22, 22 note: use '==' to turn this assignment into an equality comparison
7, 17 warning: unused variable 'A'
14, 14 warning: variable 'i' is uninitialized when used here
8, 10 note: initialize the variable 'i' to silence this warning
此外,当下降到第二个for()
循环时,i
再次没有初始化,而是保留完成第一个循环时的值。它需要重新初始化为零才能使第二个循环正常工作......(注意,我的编译器没有标记这个,幸运的是我被告知学习如何设置和使用我在这里做的断点,让我i
在运行时发现 的价值。
按照上述警告提供的指导,进行了修改以允许代码运行,并按照您描述的方式进行操作。
有关对上述警告的响应,请参阅在线评论:
int main(void)//added void to match accepted prototype of main
{
char T[100] = {0},A;//A is not used, should be deleted
//initialize array to all zeros.
int i=0,N=0,b=0;//initialized i (and N)
printf("give the number of your table's columns \n");
scanf("%d", &N);
if (N > 0 && N <= 100) {
for (i; i < N; i++) {
scanf("%c", &T[i]);
printf("give the character of the column number %d \n", i);
scanf("%c",&T[i]);
}
// `i` is already equal to N here. it will never enter the loop
//for (i; i < N; i++) {
for (i = 0; i < N; i++) {//initialized i to zero
//if (T[i] = 'A') b++;//this is not what you want
if (T[i] == 'A') b++; //replace assignment '='
//with comparison '==' operator
//Note, optionally move the following printf() statement to below
//the loop so it is called only once after counting is done.
printf("the number of characters equal to A is %d\n",b);//added '\n' for readability of output.
}
//return 0;// not here...
}
return 0;// ...but here
}
推荐阅读
- excel - 从给定行Excel VBA复制/粘贴特定单元格
- python - TPE(来自 Optuna)是否考虑试验次数?
- jmeter - 如何将所有响应保存到循环计数超过一个的文件中?
- c++ - 运行时错误:加载未对齐的地址
- python - 如何从 Pandas DataFrame 中读取 json 对象列表?
- flutter - 输入'列表
' 不是类型 'FutureOr 的子类型 ' - java - POI Excel 日期时间格式取决于地区
- java - 使用 log4j2 从 jboss 服务器中分离日志
- python - 如何正确启动位于 Python 3.7 子文件夹中的 CGI http.server?
- ruby - Nokogiri:没有子节点的非破坏性打印节点