计算器程序无法编译

Set*_*iba -7 c++ compiler-errors switch-statement

我写了一个实现简单计算器的程序.但是,它没有编译.编译器说有22个错误,我不知道为什么.

期望的行为:

  1. 询问用户所需的操作
  2. 向用户询问参数
  3. 输出结果

具体问题或错误:

在任何发生编译错误cin,cout,endl,casebreak

最小,完整和可验证的示例:

#include <iostream>
int main()
{
    float area, r, l, h, b;
    int choice;
    cout<<"\n area of?";
    cout<<"\n[1]square \n[2]rectangle \n[3]circle \n[4]triangle"<<endl;
    cin>>choice;
    switch(choice);
    {
    case 1:
        cout<<"enter length"<<endl;
        cin>>l;
        area=l*l;
        cout<<area<<endl;
        break;
    case 2:
        cout<<"enter height"<<endl;
        cin>>h;
        cout<<"enter length"<<endl;
        cin>>l;
        area=l*h;
        cout<<area<<endl;
        break;
    case 3:
        cout<<"enter radius"<<endl;
        cin>>r;
        area=r*r*3.14;
        cout<<area<<endl;
        break;
    case 4:
        cout<<"enter height"<<endl;
        cin>>h;
        cout<<"enter breadth"<<endl;
        cin>>b;
        area=h*b*0.5;
        cout<<area<<endl;
        break;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Bla*_*aze 5

这是两个错误(编译时错误,至少).首先cin,cout并且endl不知道,你必须把它们写成std::cin,std::coutstd::endl.

第二个问题在这里:

switch (choice);
Run Code Online (Sandbox Code Playgroud)

删除那个分号,没关系.为什么它不使用分号的共鸣是因为switch (choice);它是自己的并且完成了交易,如果没有它,它之后的声明就没有意义.

此外,虽然它不会导致任何编译时错误,但我强烈建议您正确缩进代码.mjcs编辑了您为您提供的代码,它现在看起来更好,并且更容易以这种方式找到错误.在一个大型程序中,代码缩进是绝对重要的,否则很难处理.

  • 我将删除关于`using namespace std;`的段落 - 或者至少更强烈地说出这样做是非常糟糕的主意.(让我们教初学者好习惯,不是坏习惯.有一天,有人可能需要和她/他的代码一起工作.可能是你......) (2认同)