最近我在做一个项目,询问用户的姓名、年龄,并通过返回的响应来确认或拒绝上述信息。我被代码中的这个错误消息难住了,我所做的每一次修改都只会产生更多的错误,我不确定我到底做错了什么。代码如下:
#include "cs50.h"
#include <stdio.h>
int main(void);
{
//ask the user for their name
string name = GetString();
//prompts the user for their name
scanf("What is your name?:%sn", name);
printf("Hellon");
}
int age = GetInt();
{
//ask user for their age
scanf("How old are you:%in", age);
printf("You are:n");
}
//Ask user to confirm
char confirm = GetChar();
{
if(confirm == 'Y' || 'y');
printf("Thank you!");
}
else if(confirm == 'N' || 'n');
{
printf("Denied");
}
}
编译此代码会返回以下错误:
project.c:13:12: error: initializer element is not a compile-time constant
int age = GetInt();
^~~~~~~~
project.c:14:1: error: expected identifier or '('
{
^
project.c:21:17: error: initializer element is not a compile-time constant
char confirm = GetChar();
^~~~~~~~~
project.c:22:2: error: expected identifier or '('
{
^
project.c:26:3: error: expected identifier or '('
else if(confirm == 'N' || 'n');
^
project.c:27:2: error: expected identifier or '('
{
^
project.c:30:2: error: extraneous closing brace ('}')
}
^
7 errors generated.
我尝试过删除%i
和%s
,但这只会产生更多错误,我尝试过在int main (void);
之后删除;
,并产生更多错误。我并不是我做错了什么才产生这些错误,任何帮助都将不胜感激。谢谢大家,干杯!
作为一个整体,整个程序都充满了不需要的行,比如if
和else
末尾的;
这不是我第一次从使用cs**.h
的人那里看到,他们不确定哪里出了问题。
并且混合了main函数中的所有函数定义和调用。
请参阅下面的程序如何使用函数声明、调用和定义都是内联注释的。
参考c 中的函数语法
#include "cs50.h"
#include <stdio.h>
// function declarations
int GetChar();
int GetInt();
int main(void)
{
/*
//ask the user for their name
string name = GetString();
//prompts the user for their name
scanf("What is your name?:%sn", name);
*/
printf("Hellon");
// function call
int age = GetInt();
printf("You are: %dn", age);
//Ask user to confirm
printf("Enter Y/y or N/n");
char confirm = GetChar();
if(confirm == 'Y' || confirm == 'y')
printf("Thank you!");
else if(confirm == 'N' || confirm == 'n')
printf("Denied");
return 0;
}
//function definitions
int GetChar()
{
char ch;
scanf(" %c", &ch);
return ch;
}
int GetInt()
{
int age;
//ask user for their age
printf("How old are you:");
scanf("%i", &age);
return age;
}
您的语句不在函数内部,因此在编译时对其进行处理以填充"全局";部分。因此,编译器必须能够静态计算age
的初始值。
由于您正在调用一个函数,因此不可能出现错误。