我是 C 新手,有以下代码:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
string s = get_string("Enter string: ");
int measure = 0;
for(int i = 0; i < strlen(s);i++)
{
if(isalpha(s[i])==0)
{
measure++;
}
}
printf("Measure is now %i\n", measure);
}
如果我将 printf 放在循环中,我可以正确地看到测量递增,但是当循环完成后我有 printf 时,它会返回到零。我相信这是一个范围问题,但我的理解是,在循环外部声明的变量(在本例中为度量)具有主函数的范围,因此可以在 for 和 while 循环中进行修改。我认为这是错误的,我不确定如何在循环范围内获取传递回主函数的值。
编辑:我将按原样保留这篇文章,以便下面的评论有意义。 @MaroBonelli 让我注意到我在两个窗口之间感到困惑,并且此代码中循环内的 printf 实际上并未打印值。
最佳答案
将我的评论转化为答案:
如果您不以某种方式明确重置该值,则该值不会重置为 0。如果您打算计算字母字符,那么此检查是错误的:
if (isalpha(s[i]) == 0)
应该是完全相反的:
if (isalpha(s[i]))
// or
if (isalpha(s[i]) != 0)
来自 isalpha
的手册页:
RETURN VALUE
The values returned are nonzero if the character c falls into the tested class, and zero if not.
关于c - 在 C 中 - 循环内递增的变量不保留值 CS50,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57129531/