开发者

simplifying and rewriting my code

开发者 https://www.devze.com 2023-04-11 01:25 出处:网络
I will be as specific as possible.. I have this code: // bintodec.cpp : Defines the entry point for the console application.

I will be as specific as possible.. I have this code:

// bintodec.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main(){
    string inp;
    int dec = 0;
    char base;
    cout << "Input a number: ";
    cin >> inp;
    cout << "Input the base your number is in: ";
    cin >> base;
    for (int i = inp.length()-1, j = 0; i >= 0; i--, ++j)
        dec += (inp[i]-48) * pow((float)base-48, j);
    cout << "Your number in base 10 is: " << dec <<endl;
    system("pause");
    return 0;
}

I'm trying to REWRITE/SIMPLIFY IT..to:

{
    int j=0,x;
    double dec,y;
    for(int i = inp.length()-1; i >= 0; i--) 
    {
    x=(inp[i]-48);
    y=pow((float)base-48, j);
    dec=dec + x * y;
    ++j;
    }
}

I have:

int j=0,x;
    double dec, y;
        char base, inp;

        cout << "Input a number: ";
    cin >> inp;
    cout << "Input the base your number is in: ";
    cin >> base;


        {
            for (int i = inp.length()-1; i>=0; --i)
            x=(inp[i]-48);
            y=pow((float)base-48, j);
            dec=dec + (x*y)
                ++j;
            {
             return 0;

For some reason its not working..visual studio is reporting that:

  1. left of '.length' must have class/struct/union type is 'char'
  2. 开发者_StackOverflow中文版
  3. subscript requires array or pointer type
  4. '++' needs l-value
  5. syntax error : missing ';' before identifier 'j'

I want to rewrite and simplify it..help with errors please..thanks!


1: You can't do inp.length() because you declared inp as a char. And a char isn't a string.

Try declaring inp as a string:

string inp;

2: "subscript requires array or pointer type"

Same reason as above. inp is a char and not an array or a string.

3/4: "'++' needs l-value"

You're missing a semicolon after: dec=dec + (x*y)

0

精彩评论

暂无评论...
验证码 换一张
取 消