Mer*_*ajA -2 c++ visual-studio-2013
对我来说,这段代码似乎没有错误,而且我学习C++的方式也是正确的.可能有什么不对?
这是我的代码:
#include<iostream>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
double Calculation(long double x, long double y);
void Output(long double s, long double d, long double p, long double q);
void main(){
long double a;
long double b;
long double sum;
long double difference;
long double product;
long double quotient;
cout << "Enter your first number." << endl;
cin >> a;
cout << "Enter your second number." << endl;
cin >> b;
Calculation(a, b);
Output(sum, difference, product, quotient);
system("pause");
}
double Calculation(long double x, long double y){
long double sum;
long double difference;
long double product;
long double quotient;
sum = x + y;
difference = x - y;
product = x * y;
quotient = x / y;
return sum;
return difference;
return product;
return quotient;
}
void Output(long double s, long double d, long double p, long double q){
cout << "The sum of your numbers is " << s << "." << endl;
cout << "The difference between your numbers is " << d << "." << endl;
cout << "The product of your numbers is " << p << "." << endl;
cout << "The quotient of your numbers is " << q << "." << endl;
}
Run Code Online (Sandbox Code Playgroud)
说明:这是一个按变量'a'和'b'工作的计算器.它通过函数Calculate计算'a'和'b'的和,差,乘积和商,并用函数Output输出答案.
Error: uninitialized local variable 'quotient' used.
uninitialized local variable 'product' used.
uninitialized local variable 'difference' used.
uninitialized local variable 'sum' used.
Run Code Online (Sandbox Code Playgroud)
您的代码有很多问题,但是有一个根本原因 - 对return语句如何工作的误解.
你有一个多return语句的功能.您似乎认为所有这些陈述都会执行; 那个假设是不正确的.只return执行函数中的第一个语句; 其余的被忽略了.
而且,您似乎暗示该return语句会自动影响调用者中的变量; 它不会.为了修改调用者中的变量,调用者本身需要分配返回的值.
如果您需要函数返回多个值,则需要更改方法:它应该通过引用获取多个参数,并修改它们,如下所示:
void Calculation(long double x, long double y, long double &sum,
long double &difference, long double &product, long double "ient) {
sum = x + y;
difference = x - y;
product = x * y;
quotient = x / y;
}
Run Code Online (Sandbox Code Playgroud)
您还需要更改原型声明Calculation,如下所示:
void Calculation(long double x, long double y, long double &sum,
long double &difference, long double &product, long double "ient);
Run Code Online (Sandbox Code Playgroud)
Calculation像这样打电话:
Calculation(a, b, sum, difference, product, quotient);
Run Code Online (Sandbox Code Playgroud)
这将解决您的编译问题,代码将正确运行.
| 归档时间: |
|
| 查看次数: |
385 次 |
| 最近记录: |