c++ - 未初始化变量和返回错误

标签 c++

我的程序有一些我不明白的问题。 在第 72 行,我收到错误:“错误 C4700:使用了未初始化的局部变量‘sumInEuros’”,但是当我使用它来存储计算时它肯定被初始化了吗? 同样在第 66 行,我收到“错误 C4716:'showPriceInEuros':必须返回一个值”- 为什么必须返回一个值?该函数只是为了向控制台输出一条消息。

我使用的是 VS13,它是 C++。 任何帮助将不胜感激,因为我被困住了! 谢谢!

#include <iostream>         //for cin >> and cout <<
#include <cassert>          //for assert
#include <iomanip>          //for endl
#include <Windows.h>

using namespace std;

void processAPrice();
int getPriceInPounds();
int convertPriceIntoEuros(int pounds);
int showPriceInEuros(int pounds, int euros);
int calculateSum(int euros);
void produceFinalData(int sum, int numberOfPrices);

int main()                  
{
    char answer('Y');
    int numberOfPrices(0);

    while (answer = 'Y')
    {
        processAPrice();
        numberOfPrices++;
        cout << "Continue? (Y/N)";
        cin >> answer;
    }

    if (numberOfPrices > 0)
        //produceFinalData(sum, numberOfPrices);


    system("PAUSE");    //hold the screen until a key is pressed
    return(0);
}


void processAPrice()    //
{
    int pounds = getPriceInPounds();
    int euros = convertPriceIntoEuros(pounds);
    int sum = showPriceInEuros(pounds, euros);
    calculateSum(euros);
}

int getPriceInPounds()      //
{
    int priceInPounds;
    cout << "Enter a price (in Pounds): /234";
    cin >> priceInPounds;
    return priceInPounds;
}


int convertPriceIntoEuros(int priceInPounds)    //
{
    const int conversionRate(0.82);
    return priceInPounds / conversionRate;
}

int showPriceInEuros(int pounds, int euros) //
{
    SetConsoleOutputCP(1252);

    cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}


int calculateSum(int euros)     // 
{
    int sumInEuros;
        sumInEuros = (sumInEuros + euros);
    return sumInEuros;
}

void produceFinalData(int sum, int numberOfPrices)      // 
{
    SetConsoleOutputCP(1252);
    cout << "The total sum is: \u20AC" << sum;
    cout << "The average is: \u20AC" << (sum/numberOfPrices);
}

最佳答案

好吧,showPriceInEuros 函数没有返回它 promise 在其签名中返回的 int。那就是错误。

如果函数不应该有返回值,你应该将它的返回类型声明为void:

void showPriceInEuros(int pounds, int euros);
//^^

然后:

void showPriceInEuros(int pounds, int euros) {
    SetConsoleOutputCP(1252);
    cout << "The Euro value of /234" << pounds << "is: \u20AC" << euros;
}

当然。

关于c++ - 未初始化变量和返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21526505/

相关文章:

c++ - 为什么要在 if 条件下进行解析?

c++ - 如何在 Windows 中获取 PyErr_Print 的输出或将其保存为字符串

c# - Swig:如何将生成的 C# 类的可访问性从 `public class` 更改为 `internal class`

c++ - SDL iOS 禁用事件泵

c++ - 使用 MICO (CORBA) 从 IDL 文件生成 C++ 类

c++ - 当 >> 字符串流时更改双引号的行为

c++ - 有空流吗?可选打印

c++ - 创建全局动态分配数组

c++ - 模板中的隐式转换和编译器强制

c++ - XPATH 包含(字符串,字符串)不工作