简单的计算器程序出了什么问题

What is wrong with simple calculator program?

本文关键字:什么 问题 程序 计算器 简单      更新时间:2023-10-16
#include <iostream>
#include <iomanip>
using namespace std;
int calculate ()
{
double a;
double b;
a =(3.0);
b =(5.0);
cout << "  " << fixed << setprecision (1) << a << "n" << endl;
cout << "* " << fixed << setprecision (1) << b << "n" << endl;
cout << "------" << endl;
cout << fixed << setprecision (2) << a*b << "n" << endl;
system("PAUSE");
return 0;
}
int calculate(int a, int b, int c)
{
double a;
double b;
double c;
a =(7.1);
b =(8.3);
c =(2.2);
cout << "  " << fixed << setprecision (1) << a << "n" << endl;
cout << "* " << fixed << setprecision (1) << b << "n" << endl;
cout << "- " << fixed << setprecision (1) << c << "n" << endl;
cout << "------" << endl;
cout << fixed << setprecision (2) << (a*b)-c << "n" << endl;
system("PAUSE");
return 0;
}

问题:为什么我必须更改double--->int?有什么突出的错误吗?

以下是输出:1> ------生成已启动:项目:HW1-2,配置:调试Win32------1> HW1-2.cpp1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(21):错误C2082:重新定义形式参数"a"1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(22):错误C2082:重新定义形式参数"b"1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(23):错误C2082:重新定义形式参数"c"1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(24):警告C4244:"=":从"double"转换为"int",可能丢失数据1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(25):警告C4244:"=":从"double"转换为"int",可能丢失数据1> c:\users\asus\desktop\hw1-2\hw1-2\ hw1-2.cpp(26):警告C4244:"=":从"double"转换为"int",可能丢失数据==========生成:0成功,1失败,0最新,0跳过==========

您有两个函数,都命名为main()。我不确定您想要实现什么,但函数在名称空间中必须具有唯一的名称。

你可以随心所欲地命名你的函数。main()是特别的——它是程序的入口点,在程序运行时被调用。如果你有另一个函数,如果你想执行它,你需要从main()内部自己调用它:

int foo(int c)
{
return c + 2;
}
int main()
{
int a = 1;
int b = foo(a);
return b;
}

您的问题很可能出现在以下行:

(a*b)c

你想在这里完成什么?编译器应该抱怨缺少分号。它不是有效的c++。您需要在(a*b)c之间指定另一个操作数(+、-、*等)

(a*b)c<--错误

如果你想相乘,它应该是(a*b)*c

EDIT-似乎您想做这个(a*b) - c,它也可以写成a*b - c

正如Caleb所说,您有两个main()声明。没有第二个主函数的代码编译得很好:

#include <iostream>
#include <iomanip>
int main()
{
double a;
double b;
double c;
a = (7.1);
b = (8.3);
c = (2.2);
std::cout << std::fixed << std::setprecision(1) << std::endl;
std::cout << "  " << a << "n" << std::endl;
std::cout << "* " << b << "n" << std::endl;
std::cout << "- " << c << "n" << std::endl;
std::cout << "------" << std::endl;
std::cout << std::setprecision(2) << (a * b) - c << "n" << std::endl;
return 0;
}

如果您希望这是一个单独的函数,可以将其重命名为其他函数,例如int calculator()

我同意caleb:

您有两个main函数。由于您的错误消息指向第21行,正好是main的第二个definition开始的地方,我认为这是第一个错误。在那之后,你会出现乘法错误,你按照别人的说法忽略了运算符。

定义和声明差异的解释

只是一个风格提示:就我个人而言,我觉得写function(param1, param2, ...)而不是function (param1, param2, ...)(注意缺少空格)很方便,因为myDefinedSomething(variableaccess)和myDefinedSomething()(functioncall)之间有区别。(你也可以访问functionspointers,在这种情况下,你会忽略paranthes,但在你应该关心它之前,你还有一点需要学习)。

正如评论中所说,试着缩进你的代码,这会让它更可读,考虑一下:

for(int i=1,i<10; i++){
if(i%3) {
if(flag){
cout<<"a";
}else{
cout<<"b";
}
}

for(int i=1,i<10; i++){
if(i%3) {
if(flag){
cout<<"a";
}else{
cout<<"b";
}
}

你最先注意到丢失的}是哪一个?