我的 cout 上有一个奇怪的输出,它把答案放在第一位,然后在我调用它的地方放一个奇怪的输出.我该怎么办?

I am getting a weird output on my cout, it puts the answer first then puts a weird output where I call it. What do I do?

本文关键字:输出 调用 方放一 我该怎么办 cout 有一个 我的 放在第一位 答案 然后      更新时间:2023-10-16
#include <iostream>
using namespace std;
//MainFunctions
int computeDiscount(int);
int mainProgram();
int main()
{
mainProgram();
}
int computeDiscount(int total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
cout << total;
}
}
int mainProgram()
{
int t;
cout << "What is the total amount for today? " << endl << ">>>";
cin >> t;
cout << "The total is: " << computeDiscount(t);
}
Output: 
What is the total amount for today?
10
7The total is: 5007456

我该怎么办?我想让七个去"5007456"出现的地方

如果我把函数放在 cout 之外,它可以工作......不确定

我想在 cout 中调用函数

这是因为您实际上并没有computeDiscount函数返回计算值。由于未定义的行为,您在字符串"The total is: "之后看到的是垃圾号码。隐式返回的值的性质是不确定的。g++添加一个额外的标志-Wall可以让您捕获该警告([-Wreturn-type](

该函数应该返回如下值

int computeDiscount(int total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
}
return total; 
}

同样,您应该在末尾有一个mainProgram()的返回值,以指定程序的成功终止。

另请参阅为什么要避免在程序中using namespace std。请参阅为什么using namespace std;被视为不良做法?。同样在C++中,您完全可以将total变量作为引用传递并对其进行操作。类似的东西

void computeDiscount(int&);
void computeDiscount(int& total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
}
}
int mainProgram()
{
int t;
std::cout << "What is the total amount for today? " << std::endl << ">>>";
std::cin >> t;
computeDiscount(t);
std::cout << "The total is: " << t << std::endl;
return 0;
}

int computeDiscount(int total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
cout << total;
}
}
在此方法中,您不会返回任何假设存在的整数,并且在 main 函数中,您正在尝试打印输出,这将为您提供垃圾值。

#include <iostream>
using namespace std;
//MainFunctions
int computeDiscount(int);
int mainProgram();
int main()
{
mainProgram();
}
void computeDiscount(int *total)
{
if (*total >= 10 && *total <= 19)
{
*total = (*total-(*total * .2));
}
}
int mainProgram()
{
int t;
cout << "What is the total amount for today? " << endl << ">>>";
cin >> t;
computeDiscount(&t);
cout << "The total is: " << t;
return 0;
}

或者你可以传递对函数的引用

代替cout << total;
return total;

int computeDiscount(int total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
return total;
}
}

正确地执行,即采用最具 C/C++ 优势的功能

int computeDiscount(int total)
{
if (total >= 10 && total <= 19)
return total -= total / 5 ;
return   
}

在函数 computeDiscount(int&( 中使用引用传递

int computeDiscount(int&);
int computeDiscount(int& total)
{
if (total >= 10 && total <= 19)
{
total = (total-(total * .2));
cout << total;
}
}