MT2 Fall 2020 Solutions
Fahrenheit
fahr.cpp
#include <iostream>
using namespace std;
int main()
{
// declare necessary variables and complete your
// code below
double f1, f2, f3, mymin;
char units;
cin >> f1 >> f2 >> f3 >> units;
if(units == 'c') {
f3 = 9*f3/5 + 32; // anything that ensures appropriate 'double' arithmetic
}
// In this approach, it needs to <= to correctly handle ties
// Look at the implementation carefully when grading to ensure
// ties are handled correctly.
if(f1 <= f2 && f1 <= f3) {
mymin = f1;
}
else if( f2 <= f1 && f2 <= f3) {
mymin = f2;
}
else {
mymin = f3;
}
// Your last action should be to output the minimum temperature
// (in degrees Fahrenheit). Do not print any text, just the
// temperature and a newline.
cout << mymin << endl;
return 0;
}
Divisible By 2 or 3
cnt23.cpp
#include <iostream>
using namespace std;
int main()
{
// Declare necessary variables and complete your
// code below. Final outputs should be made with
// just the sum on a single line.
// Need to initialize sum if code is going to
// add or subtract from it.
int sum = 0;
int val;
cin >> val;
while( val != 0 && val != 13) {
if(val > 0) {
// If number is divisible by both, the sum will be unchanged
// because we added and subtracted it.
// It is fine to have an if..else if.. structure to make
// mutually exclusive options for divisible by 2 but not 3 and
// divisible by 3 but not 2. As long as it works it is fine.
if(val % 2 == 0) {
sum += val;
}
if(val % 3 == 0) {
sum -= val;
}
}
// Get next input
cin >> val;
}
// Print the final sum result
cout << sum << endl;
return 0;
}
Same Number of Digits
samedig.cpp
// Function prototype - Complete the definition below
// Description: Function to count how many decimal digits
// an integer requires
// Input parameter: val - A non-negative integer
// Return value: number of decimal digits in 'val'
// Example: numDigits(192) should return 3.
int numDigits(int val);
int main()
{
int vals[100];
int n;
cin >> n; // you may assume n is an even number
// in the range: 0 <= n <= 100
// write a loop to recieve the n integers of input
// from the keyboard and then complete the remainder of the
// code to print 'yes' or 'no', appropriately.
// You must use the numDigits function by calling it at least once.
for(int i=0; i < n; i++) {
cin >> vals[i];
}
// Can also use an int to count how many match
// and then check for n/2 matches at the bottom.
bool same = true;
for(int i=0; i < n/2; i++) {
int nda = numDigits(vals[i]);
int ndb = numDigits(vals[n/2+i]);
if(nda != ndb) {
same = false;
break; // not necessary...fine to go through entire array
}
}
if(same == true) {
cout << "yes" << endl;
}
else {
cout << "no" << endl;
}
return 0;
}
// See prototype above for description of
// this function.
int numDigits(int val)
{
// Complete the code for this function
// Solution which handles an input of 0 (returns 1)
int nDigits = 1;
while(val >= 10) {
nDigits++;
val /= 10;
}
return nDigits;
}
