从用户输入中打印多次
printf a number of times from user input
我在做cs50。我是 C 的新手。我对 Python 的了解有限,但有些语法我不明白。
如何让它根据用户输入打印多次?为什么 void cough(int n = get_int("number: "))
不起作用?它给了我一个 use of undeclared identifier 'n'
错误。
#include <stdio.h>
#include <cs50.h>
void cough(int n);
int main(void)
{
cough(n);
}
void cough(int n = get_int("number: "))
{
for (int i = 0; i < n; i++)
{
printf("cough\n");
}
}
您不能像 C 中那样为方法初始化变量。相反,在 main
函数中分配变量并使用 scanf
将其传递给 cough
。
printf("Enter the value to be stored in n: ");
scanf("%d",&n);
printf("n= %d",n);
scanf
从stdin
读取数据,并根据参数格式将它们存储到附加参数指向的位置。
语法为:int scanf ( const char * format, ... );
首先,在 main 函数的(局部或全局)中没有名称为 'n' 的变量,您不能将变量作为参数传递,除非您声明它,先声明它然后只是将它传递给函数。
其次,你不能在函数声明中为变量赋值,在python中这个赋值意味着它将是一个默认值,但在c中这是不允许的。
#include <stdio.h>
#include <cs50.h>
void cough(int n);
int main(void)
{
int n = 0;
cough(n);
}
void cough(int n)
{
n = get_int("Enter an integer: ");
for (int i = 0; i < n; i++)
{
printf("cough\n");
}
}
我在做cs50。我是 C 的新手。我对 Python 的了解有限,但有些语法我不明白。
如何让它根据用户输入打印多次?为什么 void cough(int n = get_int("number: "))
不起作用?它给了我一个 use of undeclared identifier 'n'
错误。
#include <stdio.h>
#include <cs50.h>
void cough(int n);
int main(void)
{
cough(n);
}
void cough(int n = get_int("number: "))
{
for (int i = 0; i < n; i++)
{
printf("cough\n");
}
}
您不能像 C 中那样为方法初始化变量。相反,在 main
函数中分配变量并使用 scanf
将其传递给 cough
。
printf("Enter the value to be stored in n: ");
scanf("%d",&n);
printf("n= %d",n);
scanf
从stdin
读取数据,并根据参数格式将它们存储到附加参数指向的位置。
语法为:int scanf ( const char * format, ... );
首先,在 main 函数的(局部或全局)中没有名称为 'n' 的变量,您不能将变量作为参数传递,除非您声明它,先声明它然后只是将它传递给函数。 其次,你不能在函数声明中为变量赋值,在python中这个赋值意味着它将是一个默认值,但在c中这是不允许的。
#include <stdio.h>
#include <cs50.h>
void cough(int n);
int main(void)
{
int n = 0;
cough(n);
}
void cough(int n)
{
n = get_int("Enter an integer: ");
for (int i = 0; i < n; i++)
{
printf("cough\n");
}
}