结构问题1.cpp
// Struct Problem 1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "structs.h"
double calculateEarnings(Advertising aDay);
void displayEarnings(int questionInstance, Advertising aDay);
void mainQuestions();
int _tmain(int argc, _TCHAR* argv[])
{
mainQuestions();
return 0;
}
double calculateEarnings(Advertising aDay)
{
std::cout << aDay.usersClicked; //debug
return aDay.totalAdsShown * aDay.usersClicked * aDay.averagePerAd;
}
void takeInData(int questionInstance, Advertising aDay)
{
if (questionInstance == 0)
{
std::cin >> aDay.totalAdsShown;
}
else
if (questionInstance == 1)
{
std::cin >> aDay.usersClicked;
}
else
if (questionInstance == 2)
{
std::cin >> aDay.averagePerAd;
}
std::cin;
}
void mainQuestions()
{
static Advertising aToday;
aToday.totalAdsShown = 0;
aToday.usersClicked = 0.00;
aToday.averagePerAd = 00.00;
std::cout << "Welcome! Please input the advertising data for today." << "\n";
std::cout << "How many ads were shown today?" << "\n";
takeInData(0, aToday);
std::cout << "What percentage of users clicked our ads? (decimal form)" << "\n";
takeInData(1, aToday);
std::cout << "What were the average earnings per ad? (ex: 5.15)" << "\n";
takeInData(2, aToday);
structs.h
#ifndef STRUCTS_H
#define STRUCTS_H
typedef double percentage;
typedef double USD;
struct Advertising
{
int totalAdsShown;
percentage usersClicked;
USD averagePerAd;
};
#endif
基本上,当被“cin”调用时,不会保存数据。我添加了一行来打印aDay.usersClicked值并打印到0.我正在学习c ++,所以问题非常基础。我很感激所有提示!
谢谢
答案 0 :(得分:2)
改变这个:
void takeInData(int questionInstance, Advertising aDay)
进入这个:
void takeInData(int questionInstance, Advertising& aDay)
它会起作用。原因是在您的版本中,参数aDay
是按值传递的;即参数的副本被传递给函数。因此takeInData()
对其aDay
版本所做的任何操作都在副本中完成。 takeInData()
返回后,副本(及其中的信息)将丢失。
在已编辑的版本中,对aDay
的引用将传递给该函数。现在它将引用传递的变量,即main()
中的变量。现在takeInData()
所做的所有事情都存储在main()
中实际声明的值中。