c++ - 错误:'{' token { 之前的预期 unqualified-id
问题描述
所以我一直在我的计算机科学课上研究命令行参数,我得到了这个:
错误:'{' token { { ^
我一直在试图弄清楚它有什么问题,但在我的第一个 int 语句之后出现错误,我无法理解?这是代码。任何指导将不胜感激!在编码方面,我几乎是个菜鸟。
#include <iostream>
#include <string>
#include <sstream> // for std::stringstream
#include <cstdlib> // for exit()
using namespace std;
double int_rate;
const double RULE72 = 72;
const double YDAYS = 365;
int main(int argc, char *argv[]);
{
printf("argc = %d", argc);
double amount;
double int_rate;
int days;
int years;
cout << "What is the interest rate? ";
cin >> int_rate;
years = RULE72 / int_rate;
cout << "Your money doubles in " << years << " years.";
days = years * YDAYS;
cout << "Your money doubles in " << days << " days." << endl;
cout << "Amount you would like to see double. ";
cin << amount;
cout << "Money earned by day " << (amount * 2) / days << endl;
return 0;
}
解决方案
对这个问题的一个更明确的答案是添加一个分号 (" ;
"),它在C++和许多其他语言中被视为语句结束(除了\
用于分割行的 的用法) ......和以这些“分号”结尾的函数名被视为函数声明......所以不要将它与你想要在这里做的函数定义混淆......
函数声明是没有主体的预定义函数骨架,必须在代码中的某处定义......否则编译器会抱怨函数没有主体......
看这里:
int main(int argc, char *argv[]); // <- Semicolon
{
// Some useful and useless code here... (but not going to work anyway, so...)
}
在这里,编译器会说:
“嘿,这个函数末尾有一个分号,我知道,它是一个函数声明...... ”
当它到达下一行时,它就像:
“咦!这个函数的名字在哪里,我知道我在上一行有一个分号,所以不可能是那个! ”
编译器最终给出了一个关于主体没有声明的错误......所以,你有两个选择......
要么做这样的事情(每个人都强烈推荐)......
int main(int argc, char *argv[]) // <- Semicolon removed
{
// Some useful and useless code here...
}
或者:(不推荐,但不会造成任何问题)
int main(int argc, char *argv[]); // <- Semicolon! Meaning: Declaration!
int main(int argc, char *argv[]) // Compiler says : Oh its the body (definition) of the declaration I read in the previous line...
{
// Some useful and useless code here...
}
注意:我确信编译器会向您指出是哪一行导致了错误,因此您应该自己尝试一些方法,因为学习自己可以获得比渴望答案更多的经验......
亲切的问候,
鲁克斯。
推荐阅读
- emacs - 在 Emacs 中使用 Coq 时,如何在 ProofGeneral 中自定义命令和战术的颜色?
- react-native - React Native - 在视图边框上渲染阴影而不是在内容上
- python - 为什么我的枚举类型代码返回“对象没有属性”?
- android - 使用 adb shell 从 android sdcard 获取文件的 shell 脚本
- sage - Sage 数学数值评估
- php - 自动更改空格和句点以强调
- r - 在 R 中从 rbcb 包安装和下载数据
- python - 打印曲线拟合功能
- javascript - 如何在javascript中将字符串数组转换为对象属性?
- python - 如何将 Pandas DataFrame 转换为自定义嵌套 JSON?