【问题标题】:C++ function return problem with defined variable定义变量的C++函数返回问题
【发布时间】:2021-12-13 02:53:25
【问题描述】:

这就是问题所在:我有一个名为 func3 的函数,它使用三个输入并且应该返回基于它们的计算。但是,我无法设法从函数返回计算值。 这是我的代码:

#include <iostream>
#include <string>
#include <array>
#include <cmath>
using namespace std;
/*
bool func1(int budget){
    if( budget < 0 ) {
        cout << "Budget cannot be negative."<< endl; 
        return false; 
    }
    else {
        return true; 
    }
}
bool func2(int num1, int num2, int num3){ 
    if (int num1 < 0 || int num2 < 0 || int num3 < 0 ) {
        cout << "All quantities must be positive."<< endl;
        return false;
    }
    else { 
        return true;
    }
}
*/
int func3(int *p){
    
    int currentprice = *(p+0) * 5 + *(p+1) * 10 + *(p+2) * 15  ;
    cout << currentprice; cout << endl;
    return  currentprice; 

}









int main() {
    /*
    int budget;
    int num1, num2, num3;
    */
    int p1;
    int p2;
    int p3;
    int currentprice= 0;
    cin >> p1 >> p2 >> p3 ;
    int position[3] ;
    int *p;
    p= position;
    *(p+0) = p1 ; 
    *(p+1) = p2 ; 
    *(p+2) = p3 ;
    func3(p);
    cout << *(p+0) << endl;
    cout << currentprice << endl;
return 0; 
}

consol 是:

1

1

1

30

1

0

按任意键继续。 . .

其中前三个 1 是输入,其他是输出。 可以通过 30 和 0 结果检测到问题,它们对我来说应该是相同的,但我无法从函数返回 currentprice 值。

【问题讨论】:

  • 完全不清楚你的问题是什么。
  • @JosephLarson 你也许是对的。问题是:我有这个函数,它使用三个输入,应该返回一个基于它们的计算。但是,我无法设法从函数返回计算值。
  • 好的,但是您正在测试的输入是什么,结果应该是什么,您真正得到了什么?计算在做什么?你的代码是一种非常奇怪的风格,所以很难说出你想要做什么。
  • 返回到哪里?
  • 提示:您正在丢弃 func3() 的返回值。它永远不会回到 main()。

标签: c++ function variables return


【解决方案1】:

你做了一些非常奇怪的事情。这不会是一个答案,但它会解决你的一些奇怪的代码。

int position[3] ;
int *p;
p= position;
*(p+0) = p1 ; 
*(p+1) = p2 ; 
*(p+2) = p3 ;

好吧,这太恶心了。我不得不看一会儿,但我认为这更有意义:

p[0] = p1;
p[1] = p2;
p[2] = p3;

当然,你使用神秘的变量名称意味着我完全不知道这些数据应该是什么。

int currentprice = *(p+0) * 5 + *(p+1) * 10 + *(p+2) * 15  ;

同样,同样神秘。我想你的意思是:

int currentPrice = p[0] * 5 + p[1] * 10 + p[2] * 15;

当然,我完全不知道这个计算应该是什么。但这是人们期望您处理数组的方式。取消引用指针只会让人们感到困惑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2018-08-29
    • 2014-04-07
    • 2011-02-03
    • 1970-01-01
    相关资源
    最近更新 更多