I'm having a serious output problem with a program i made for my homework. Below is the code I'm using to calculate the mean and standard deviation for a group of numbers given by the user, until a flag value of -1 is reached. I am not allowed to use arrays. I am supposed to use a formula (for the std dev part) given by my professor which is ((sum (xi)^n) - ((sum xi) ^2/ n) /(n-1)) xi is x sub i, which is each input. I am using visual studio 2010 on a win7 x64 vm on my macbook pro (doubt this has anything to do, but just in case).
below is the code (followed by the screen cap of the error)
#include<iostream>
#include <cmath>
using namespace std;
int i;
int sum_unkown_vars();
double std_dev(int sum, int n);
/*double std_dev(int sum, int n)
{
double dev;
dev = sqrt(((pow(sum, 2.0)-(pow(sum, 2.0)/n)))/(n-1));
return dev;
}*/
int sum_unkown_vars()
{
i = 0;
int n;
int sum1 = 0;
int sum_sqd = 0;
double sdev;
cout<<"This part will sum variables given by user until flag value of -1"<<endl;
cout<<"\nNext Variable Please: ";
cin >> n;
while(n != -1)
{
sum_sqd = sum_sqd + n*n;
sum1 = sum1 + n;
i++;
cout<<"\nNext Variable Please: ";
cin >> n;
}
cout <<"\nNumber of variables is "<< i <<endl
<<"Sum of variables is "<< sum1 <<endl;
sdev = sqrt(((sum_sqd*1.0)-(1.0*pow(sum1, 2.0)/n))/(n*1.0-1.0));
cout <<"\nStandard Deviation is "<< sdev << endl;
return sum1;
}
int main()
{
int sum = 0;
int j;
double avg;
double std_dev1;
cout<<"This program will take integers given by the user,"
<<"\nsum them, then find average and standard deviation\n\n";
sum = sum_unkown_vars();
//cout <<"\nPlease enter number of integers previously given: ";
//cin >> j;
avg = sum / (i*1.0);
cout <<"\nAverage is: "<<avg<<endl;
//std_dev1 = std_dev(sum, i);
//cout <<"Standard Deviation is : "<< std_dev1 <<endl;
system("pause");
return 0;
}
Thanks in advance for any help received
The variable n in the formula
((sum (xi)^n) - ((sum xi) ^2/ n) /(n-1))
And the variable 'n' in the function
sum_unkown_vars()
are not the same. The n in the formula indicates the number of elements and this is defined by the variable 'i' in your program. Please correct this first.
Additionally number of variables should be either i+1 or you should increment i just after the initial reading.
I think there are still more errors in the code. e.g, you don't return the standard deviation from the function, you are using integer to return the standard deviation etc. Please debug the rest yourself with a debugger. Please make an expectation for the values and cross check it in the debugger.
Related
I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.
According to my lecturer a balanced number is balanced if the sum of its divisors is equal to it self. for example: 6 is a balanced number because 1+2+3=6
These are my very first homework so i am struggeling.
#include <iostream>
using namespace std;
int main() {
int num = 0;
int sum = 0;
cout << "Enter a number" << endl;
cin >> num;
if (num % (num-1) == 0 ){
for(int i =1; sum == 0; i++) {
sum += (num - i);
}
if (sum == num) {
cout << "Great Success" << endl;
}
else {
cout << "Wrong number" << endl;
}
}
}
Do the maths first. Often code being a bit messy is just a consequence of not preparing yourself good enough to write the code. Dont start writing code before you know what you want to write. Frankly, from your code one can see that it is something related to num-1 dividing num, but otherwise it is not clear how it is supposed to solve the problem. And its intendation makes it quite hard to read, so lets forget about the code and start from scratch...
y is a divisor of x exactly if x % y == 0. The biggest possible divisor of x is x/2. To get all divisors we can simply check every number from 2 up to x/2 (1 is always considered a divisor, hence no need to check).
Only now we can write some code:
int x;
std::cin >> x;
int sum = 1;
for (int y = 2; y <= x/2; ++y){
if ( check_if_y_is_divisor) { sum += y; }
}
bool is_balanced = sum == x;
I left a tiny hole in the code that you have to fill (I just dont like to give away the full solution when it is homework).
I used Dev c++ 5.5.3 to write some programs. one of the programs is about getting some numbers (integer) until zero and then prints max, min , avg. In my computer everything is fine. in someone else computer, it does not show the right average and it shows very strange numbers 4.612521 e+8 and like this. I define a variable avg and calculate the value and then print it. The other one calculate the average directly when calling cout. can someone check This programs:
Program 1 which doesn't show the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
avg = (float) s/count ;
cout<<"Average: "<<avg<<endl; // NOTE NOTE NOTE NOTE
return 0;
}
Program 2 which shows the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
//avg = (float) s/count ;
cout<<"Average: "<<(float) s/count<<endl; //NOTE NOTE NOTE NOTE
return 0;
}
Both programs have undefined behaviour because s is not initialised and has not been assigned a value before you try to read from it for the first time:
int max , min , count = 0 , s;
[...]
s+=n;
All behaviour you have seen and the fact that it apparently "worked" on your computer and did "not work" on someone else's were more or less random occurrences.
Here's an easy fix:
int max , min , count = 0 , s = 0;
Note that your compiler should have warned you about the uninitialized variable. If not, then perhaps you should choose a higher warning level.
Also note that there are a lot of other flaws in your program, for example the use of using namespace std, that you declare multiple variables on the same line or that some of your variable names are not very descriptive.
I am making a C++ program to calculate the square root of a number. This program does not use the "sqrt" math built in operation. There are two variables, one for the number the user will enter and the other for the square root of that number. This program does not work really well and I am sure there is a better way to do so:
Here is my full code:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot != number){
squareroot+=0.1;
}
cout << "the square root is" << squareroot << endl;
return 0;
}
I know there must be a better way. Pls help. Looked through Google but don't understand the complex programs there as I am still a beginner.
Thanks in advance.
Below explanation is given for the integer square root calculation:
In number theory, the integer square root of a positive
integer n is the positive integer m which is the greatest integer less
than or equal to the square root of n
The approach your started is good but needs several correction to make it work:
you are working with int you want to add 1 to squareroot not 0.1
you want to stop your calculation when you squareroot * squareroot is equal or greater than number. Think about the case were the number is 26, you don't have an integer that multiplies itself to 26.
in the case of number equal to 26, do you want to return 5 or 6? After your while loop the value of squareroot will be 6 so you might want to reverse it to 5 (if squareroot * squareroot is different than number)
Below the exemple:
#include <iostream>
using namespace std;
int main(){
int squareroot = 0;
int number;
cout << "enter a number sp that i can calculate its squareroot" << endl;
cin >> number;
while (squareroot * squareroot < number){
squareroot+=1;
}
if (squareroot * squareroot != number) --squareroot;
cout << "the square root is" << squareroot << endl;
return 0;
}
Below a more efficient and elegant way of calculating the square root using binary search principle. O(log(n))
int mySqrt(int x) {
if (x==0) return 0;
int left = 1;
int right = x/2 + 1;
int res;
while (left <= right) {
int mid = left + ((right-left)/2);
if (mid<=x/mid){
left = mid+1;
res=mid;
}
else {
right=mid-1;
}
}
return res;
}
This function uses Nested Intervals (untested) and you can define the accuracy:
#include <math.h>
#include <stdio.h>
double mySqrt(double r) {
double l=0, m;
do {
m = (l+r)/2;
if (m*m<2) {
l = m;
} else {
r = m;
}
}
while(fabs(m*m-2) > 1e-10);
return m;
}
See https://en.wikipedia.org/wiki/Nested_intervals
This function will calculate the floor of square root if A is not a perfect square.This function basically uses binary search.Two things you know beforehand is that square root of a number will be less or equal to that number and it will be greater or equal to 1. So we can apply binary search in that range.Below is my implementation.Let me know if you don't understand anything in the code.Hope this helps.
int sqrt(int A) {
if(A<1)return 0;
if(A==1)return 1;
unsigned long long start,end,mid,i,val,lval;
start = 1;
end = A;
while(start<=end){
mid = start+(end-start)/2;
val = mid*mid;
lval = (mid-1)*(mid-1);
if(val == A)return mid;
else if(A>lval && A<val) return mid-1;
else if(val > A)end = mid;
else if(val < A)start = mid+1;
}
}
The problem with your code, is that it only works if the square root of the number is exactly N*0.1, where N is an integer, meaning that if the answer is 1.4142 and not 1.400000000 exactly your code will fail. There are better ways , but they're all more complicated and use numerical analysis to approximate the answer, the easiest of which is the Newton-Raphson method.
you can use the function below, this function uses the Newton–Raphson method to find the root, if you need more information about the Newton–Raphson method, check this wikipedia article. and if you need better accuracy - but worse performance- you can decrease '0.001' to your likening,or increase it if you want better performance but less accuracy.
float mysqrt(float num) {
float x = 1;
while(abs(x*x - num) >= 0.001 )
x = ((num/x) + x) / 2;
return x;
}
if you don't want to import math.h you can write your own abs():
float abs(float f) {
if(f < 0)
f = -1*f;
return f;
}
Square Root of a number, given that the number is a perfect square.
The complexity is log(n)
/**
* Calculate square root if the given number is a perfect square.
*
* Approach: Sum of n odd numbers is equals to the square root of n*n, given
* that n is a perfect square.
*
* #param number
* #return squareRoot
*/
public static int calculateSquareRoot(int number) {
int sum=1;
int count =1;
int squareRoot=1;
while(sum<number) {
count+=2;
sum+=count;
squareRoot++;
}
return squareRoot;
}
#include <iostream>
using namespace std;
int main()
{
double x = 1, average, s, r;
cout << "Squareroot a Number: ";
cin >> s;
r = s * 2;
for ( ; ; ) //for ; ; ; is to run the code forever until it breaks
{
average = (x + s / x) / 2;
if (x == average)
{
cout << "Answer is : " << average << endl;
return 0;
}
x = average;
}
}
You can try my code :D
the method that i used here is the Babylonian Squareroot Method
which you can find it here https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
The directions are: Design and code a program that asks the user how many numbers from which to determine an average. Then prompt the user for the integer values and sum them to a total. Display the sum of the numbers and the calculated average with appropriate accompanying text. The average should be shown with 1 decimal place. Repeat the process until the user enters zero (0) as the number of values to be averaged. You may use either a "while" loop or a "do…while" loop for the main program loop.
Use one function to read and sum the values and another function to display the sum and average. Use a "for" loop to read and sum the values.
The for loop doesn't seem to be executing, but I can't figure out why.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int sumNums(int amount, int, int, int);
void displaySum(int sum, int avg);
main()
{
int amount = 0;
cout <<"How many numbers do you wish to average? ";
cin >> amount;
int avg = 0, sum = 0;
while (amount != 0)
{
for (int lim = 0; lim == amount; lim++)
{
int number = 0;
cout <<"Enter a value"<< endl;
cin >> number;
sumNums(amount, number, sum, avg);
displaySum (sum, avg);
}
}
}
int sumNums (int amount, int number, int sum, int avg)
{
sum = sum + number;
avg = sum / amount;
return sum, avg;
}
void displaySum (int sum, int avg)
{
cout <<"The sum is "<< sum <<" and the average is "<< avg << endl;
}
for (int lim = 0; lim == amount; lim++)
Here you set lim to 0 and the code runs only if amount is not 0. In your for you execute only if lim equals amount which never happens.
Whatever your condition is, it must evaluate to true for every iteration that you want to do.
Most probably, you will want to execute until lim equals amount so that means that you want it to execute for every iteration where lim is lower than amount.
for(int lim = 0; i < amount; lim++)
for (int lim = 0; lim == amount; lim++) // so wrong...
change to
for (int lim = 0; lim < amount; lim++)